小编tho*_*mas的帖子

使用python WeakSet启用回调功能

我正在研究是否可以在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 …
Run Code Online (Sandbox Code Playgroud)

python destructor weak-references callback

12
推荐指数
1
解决办法
1637
查看次数

标签 统计

callback ×1

destructor ×1

python ×1

weak-references ×1