参考周期的垃圾收集器

需要垃圾收集器的唯一时间是你有一个参考周期。参考周期的简单示例是其中 A 表示 B 而 B 表示 A,而其他任何表示 A 或 B 都不是 .A 或 B 都不能从程序中的任何位置访问,因此它们可以安全地被破坏,但它们的引用计数是 1,因此它们不能仅通过引用计数算法来释放。

>>> import gc; gc.disable()  # disable garbage collector
>>> class Track:
        def __init__(self):
            print("Initialized")
        def __del__(self):
            print("Destructed")
>>> A = Track()
Initialized
>>> B = Track()
Initialized
>>> A.other = B
>>> B.other = A
>>> del A; del B  # objects are not destructed due to reference cycle
>>> gc.collect()  # trigger collection
Destructed
Destructed
4

参考周期可以是任意长的。如果 A 指向 B 指向 C 指向……指向指向 A 的 Z,那么 A 到 Z 都不会被收集,直到垃圾收集阶段:

>>> objs = [Track() for _ in range(10)]
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
>>> for i in range(len(objs)-1):
...     objs[i].other = objs[i + 1]
...
>>> objs[-1].other = objs[0]  # complete the cycle
>>> del objs                  # no one can refer to objs now - still not destructed
>>> gc.collect()
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
20