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

问题描述 投票:1回答:1

在下面的代码中,名为a的对象是其自身的属性,它创建了一个参考循环。

class MyClass(object):
     pass

 a = MyClass()
 a.obj = a

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

我不确定为什么一定要这样的情况,即参考周期会阻止参考计数变为0。有人可以一步一步向我解释一下吗?

python python-3.x memory-management reference reference-counting
1个回答
5
投票
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()将其禁用)。它会定期运行,并且在运行时,即使余下的引用仍然存在,它也会丢弃我们的小饰品。

© www.soinside.com 2019 - 2024. All rights reserved.