编程语言
首页 > 编程语言> > python – 为什么weakref不能在这个绑定方法上工作?

python – 为什么weakref不能在这个绑定方法上工作?

作者:互联网

我有一个项目,我试图使用带有回调的weakrefs,我不明白我做错了什么.我创建了简化测试,显示了我与之混淆的确切行为.

为什么在这个测试中test_a按预期工作,但self.MyCallbackB的weakref在类初始化和调用test_b之间消失了?我想只要实例(a)存在,对self.MyCallbackB的引用应该存在,但事实并非如此.

import weakref

class A(object):
    def __init__(self):

        def MyCallbackA():
            print 'MyCallbackA'
        self.MyCallbackA = MyCallbackA

        self._testA = weakref.proxy(self.MyCallbackA)
        self._testB = weakref.proxy(self.MyCallbackB)

    def MyCallbackB(self):
        print 'MyCallbackB'

    def test_a(self):
        self._testA()

    def test_b(self):
        self._testB()

if __name__ == '__main__':
    a = A()    
    a.test_a()
    a.test_b()

解决方法:

你想要一个WeakMethod.

解释为什么您的解决方案不起作用的解释可以在配方的讨论中找到:

Normal weakref.refs to bound methods don’t quite work the way one expects, because bound methods are first-class objects; weakrefs to bound methods are dead-on-arrival unless some other strong reference to the same bound method exists.

标签:python,weak-references
来源: https://codeday.me/bug/20190927/1823333.html