__当涉及循环引用时,del\u方法未执行

2024-04-19 17:14:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现当涉及循环引用时,定制的__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

为什么会这样?在

编辑: 多亏了布伦巴恩。我找到原因了。在

del something只将something的引用计数减少1。在

__del__将仅在引用计数达到0时执行。在

以下是测试代码:

^{pr2}$

输出为:

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操作?在


Tags: thetoselfmaindefcustomreferencedel
3条回答

因为垃圾回收器无法知道哪些可以先安全删除。在

阅读documentation for ^{}和{a2}。__del__没有做你可能认为的事情,也没有{}。__del__不一定在执行del时调用,并且在循环引用的情况下可能永远不会调用。del所做的就是将引用计数减少1。在

自从python3.4以来,这已经不再是真的了。见PEP-442。在

相关问题 更多 >