【问题标题】:__del__ does not work if the instance is recorded in a class dictionnary [duplicate]如果实例记录在类字典中,__del__ 不起作用[重复]
【发布时间】:2016-09-29 18:11:38
【问题描述】:

我想在字典中注册我的班级的每个实例,键是参数之一。

这似乎可行,但 __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__ 彼此关系不大; __del__ 当然不是用于重载 del 运算符或类似的东西。
  • 您可能希望将weakref.WeakValueDictionary 用于Test.instances。请参阅有关它的文档。

标签: python class python-3.x dictionary


【解决方案1】:

__del__ 仅在代码中不再引用该对象时才被调用。当del 关键字用于对象时,它不会(必然)调用。

当您 launch 一个 Test 实例时,您最终会得到 2 个引用 - aTest.instances 字典中的一个额外引用。执行del a 只会删除引用aTest.instances 引用仍然存在,因此不会调用 __del__

管理对象引用的一种(可能)更好的方法是将weakref 存储到对象中。在这种情况下,您可能会将Test.instances 设为weakref.WeakValueDictionary

【讨论】:

  • 我明白了。非常感谢。
猜你喜欢
  • 2018-06-28
  • 2022-06-21
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 2021-12-07
  • 1970-01-01
  • 2020-06-02
相关资源
最近更新 更多