【发布时间】:2014-03-16 14:36:18
【问题描述】:
我正在研究是否可以在 python 中实现简单的回调功能。我想我也许可以为此使用weakref.WeakSet,但显然我遗漏了一些东西或误解了一些东西。正如您在代码中看到的那样,我首先尝试使用“ClassA”对象中的回调方法列表,但意识到这会使已添加到回调列表中的对象保持活动状态。相反,我尝试使用 weakref.WeakSet 但这也不起作用(至少不是这样)。最后四行代码中的注释解释了我想要发生的事情。
谁能帮我解决这个问题?
from weakref import WeakSet
class ClassA:
def __init__(self):
#self.destroyCallback=[]
self.destroyCallback=WeakSet()
def __del__(self):
print('ClassA object %d is being destroyed' %id(self))
for f in self.destroyCallback:
f(self)
class ClassB:
def destroyedObjectListener(self,obj):
print('ClassB object %d is called because obj %d is being destroyed'%(id(self),id(obj)))
a1=ClassA()
a2=ClassA()
b=ClassB()
a1.destroyCallback.add(b.destroyedObjectListener)
#a1.destroyCallback.append(b.destroyedObjectListener)
print('destroyCallback len() of obj: %d is: %d'%(id(a1),len(a1.destroyCallback))) # should be 1
a2.destroyCallback.add(b.destroyedObjectListener)
#a2.destroyCallback.append(b.destroyedObjectListener)
print('destroyCallback len() of obj: %d is: %d'%(id(a2),len(a2.destroyCallback))) # should be 1
del a1 # Should call b.destroyedObjectListener(self) in its __del__ method
del b # should result in no strong refs to b so a2's WeakSet should automatically remove added item
print('destroyCallback len() of obj: %d is: %d'%(id(a2),len(a2.destroyCallback))) # should be 0
del a2 # Should call __del__ method
更新:基于已接受答案的解决方案可以在 github 上找到:git@github.com:thgis/PythonEvent.git
【问题讨论】:
标签: python callback destructor weak-references