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 或更早的版本相同. 
复制代码

 

posted @   淋哥  阅读(1944)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示