为什么 Python 中的引用循环会阻止引用计数变为 0?
Why do reference cycles in Python prevent the reference count from going to 0?
在下面的代码中,名为a
的对象是它自己的一个属性,它创建了一个引用循环。
class MyClass(object):
pass
a = MyClass()
a.obj = a
如果我当时调用 del a
,我应该不会删除对 a
的所有引用,因为 a
的自引用性质应该防止它有一个非零的引用计数。
我不确定为什么引用循环会阻止引用计数变为 0。有人可以逐步向我解释一下吗?
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)
因此,引用计数垃圾收集器无法处理这个小饰品。幸运的是,Python 有另一个垃圾收集器,一个分代垃圾收集器(除非你禁用它,使用 gc.disable()
)。它定期运行,当它运行时,它会处理掉我们的饰品,即使悬空引用仍然存在。
在下面的代码中,名为a
的对象是它自己的一个属性,它创建了一个引用循环。
class MyClass(object):
pass
a = MyClass()
a.obj = a
如果我当时调用 del a
,我应该不会删除对 a
的所有引用,因为 a
的自引用性质应该防止它有一个非零的引用计数。
我不确定为什么引用循环会阻止引用计数变为 0。有人可以逐步向我解释一下吗?
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)
因此,引用计数垃圾收集器无法处理这个小饰品。幸运的是,Python 有另一个垃圾收集器,一个分代垃圾收集器(除非你禁用它,使用 gc.disable()
)。它定期运行,当它运行时,它会处理掉我们的饰品,即使悬空引用仍然存在。