为什么 Python 中的引用循环会阻止引用计数变为 0?

Ask*_*ker 1 python memory-management reference reference-counting python-3.x

在下面的代码中,命名的对象a是它自己的一个属性,它创建了一个引用循环。

class MyClass(object):
     pass

 a = MyClass()
 a.obj = a
Run Code Online (Sandbox Code Playgroud)

如果我当时调用del a,我应该不会摆脱对 的所有引用a,因为 的自引用性质a应该防止它具有非零引用计数。

我不确定为什么引用循环会阻止引用计数变为 0。有人可以向我解释这一点,一步一步吗?

Ama*_*dan 6

class MyClass(object):
     pass

a = MyClass()
# for clarity, let's call this object "trinket"
# (to dissociate the object from the variable)
# one reference to trinket: variable a

a.obj = a
# two references to trinket: variable a, trinket.obj

del a
# one reference to trinket: trinket.obj
# (because del doesn't delete the object, just the variable)
Run Code Online (Sandbox Code Playgroud)

因此,引用计数垃圾收集器无法处理此饰品。幸运的是,Python 有另一个垃圾收集器,一个分代垃圾收集器(除非你禁用它,使用gc.disable())。它定期运行,当它运行时,它会处理我们的饰品,即使一个悬空的引用仍然存在。