參考週期的垃圾收集器

需要垃圾收集器的唯一時間是你有一個參考週期。參考週期的簡單示例是其中 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