为什么弱引用不适用于此绑定方法? [英] Why doesn't the weakref work on this bound method?
问题描述
我有一个项目,我试图在回调中使用弱引用,但我不明白我做错了什么.我创建了简化的测试,显示了我混淆的确切行为.
I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with.
为什么在这个测试中 test_a 按预期工作,但是 self.MyCallbackB 的弱引用在类初始化和调用 test_b 之间消失了?我想只要实例 (a) 存在,对 self.MyCallbackB 的引用就应该存在,但它不存在.
Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn't.
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.
您的解决方案为何不起作用的解释可以在对配方的讨论中找到:
An explanation why your solution doesn't work can be found in the discussion of the recipe:
绑定方法的普通weakref.refs并不像人们期望的那样工作,因为绑定方法是一等对象;对绑定方法的弱引用在到达时无效,除非存在对同一绑定方法的其他强引用.
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.
这篇关于为什么弱引用不适用于此绑定方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!