在下面的代碼中,被命名的對象a是它自身的一個屬性,它創建了一個引用循環。class MyClass(object): pass a = MyClass() a.obj = a如果我當時調用del a,我應該不會擺脫對 的所有引用a,因為自引用性質a應該防止它具有非零引用計數。我不確定為什么引用周期會阻止引用計數變為 0。有人可以一步一步地向我解釋嗎?
1 回答

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
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())。它會定期運行,當它運行時,它會處理掉我們的 trinket,即使仍然有一個懸空的引用。
添加回答
舉報
0/150
提交
取消