我发现__del__
当涉及循环引用时,自定义方法似乎没有执行。
这是一个示例代码:
class DelClass():
def __init__(self,a):
self.prop = a
def __del__(self):
print 'del'
if __name__ == "__main__":
dc1 = DelClass(None)
dc2 = DelClass(dc1)#dc2 referring to dc1
dc1.prop = dc2#dc1 referring to dc2, thus creating circular reference
del dc1#not executing the custom __del__ method
dc = DelClass(1)
del dc#executing the custom __del__ method
为什么会发生这种情况?
编辑: 感谢 BrenBarn。我找到了原因。
del something
仅将引用计数减something
1。
__del__
只有当引用计数达到 0 时才会执行。
这是一个测试代码:
import gc
class DelClass():
def __init__(self,name,a):
self.name = name
self.prop = a
def __del__(self):
print '#####deleting',self.name
dc1 = DelClass("dc1",None)
dc2 = DelClass("dc2",dc1)#dc2 referring to dc1
dc1.prop = dc2#dc1 referring to dc2, thus creating circular reference
print "before deleting dc1,reference count:",len(gc.get_referrers(dc1))
del dc1#not executing the custom __del__ method
print "after deleting dc1, reference count:",len(gc.get_referrers(dc2.prop))
print "deleting the reference held by dc2"
del dc2.prop
print dc2
输出是:
before deleting dc1,reference count: 2
after deleting dc1, reference count: 1
deleting the reference held by dc2
#####deleting dc1
<__main__.DelClass instance at 0x9316dec>
#####deleting dc2
又出现了一个问题:
为什么输出中的最后一行(#####deleting dc2
)会发生?
发生了一些隐式del
操作?