python标准库介绍——14 gc 模块详解

==gc 模块==


(可选, 2.0 及以后版本) ``gc`` 模块提供了到内建循环垃圾收集器的接口. 

Python 使用引用记数来跟踪什么时候销毁一个对象; 一个对象的最后一个引用一旦消失, 这个对象就会被销毁. 

从 2.0 版开始, Python 还提供了一个循环垃圾收集器, 它每隔一段时间执行. 
这个收集器查找指向自身的数据结构, 并尝试破坏循环. 如 [Example 1-87 #eg-1-87] 所示.

你可以使用 ``gc.collect`` 函数来强制完整收集. 这个函数将返回收集器销毁的对象的数量. 

====Example 1-87. 使用 gc 模块收集循环引用垃圾====[eg-1-87]

```
File: gc-example-1.py

import gc

# create a simple object that links to itself
class Node:

    def _ _init_ _(self, name):
        self.name = name
        self.parent = None
        self.children = []

    def addchild(self, node):
        node.parent = self
        self.children.append(node)

    def _ _repr_ _(self):
        return "<Node %s at %x>" % (repr(self.name), id(self))

# set up a self-referencing structure
root = Node("monty")

root.addchild(Node("eric"))
root.addchild(Node("john"))
root.addchild(Node("michael"))

# remove our only reference
del root

print gc.collect(), "unreachable objects"
print gc.collect(), "unreachable objects"

*B*12 unreachable objects
0 unreachable objects*b*
```

如果你确定你的程序不会创建自引用的数据结构, 你可以使用 ``gc.disable`` 函数禁用垃圾收集, 
调用这个函数以后, Python 的工作方式将与 1.5.2 或更早的版本相同. 
原文地址:https://www.cnblogs.com/xuchunlin/p/7748359.html