我想在字典中注册我的类上的每个实例,键是参数之一。
这似乎有效,但是 __del__
功能失败。
这是代码:
class Test(object):
instances = {}
def __init__(self, id):
self.id = id
def launch(self):
print("launch")
Test.instances[self.id] = self
def __del__(self):
print("del")
del Test.instances[self.id]
这是我得到的不同输出:
>>> a = Test(25)
>>> del a
del
>>> a = Test(25)
>>> a.launch()
launch
>>> del a
>>>
我不明白为什么会发生这种情况,有人有建议吗?
最佳答案
仅当代码中不再有对该对象的引用时,才会调用
__del__
。当对对象使用 del
关键字时,它不会(必然)被调用。
当您启动
一个Test
实例时,您最终会得到2个引用——a
和Test中的一个额外引用.instances
字典。执行del a
只会删除引用a
。 Test.instances
引用仍然存在,因此 __del__
不会被调用。
管理对象引用的(可能)更好的方法是将weakref
存储到对象。在这种情况下,您可能会将 Test.instances
设为 weakref.WeakValueDictionary
.
关于python - 如果实例记录在类字典中,__del__ 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777235/