我正在尝试为具有循环引用的 Python 类编写终结器。我发现弱引用回调是要走的路。不幸的是,我用作回调的 lambda 似乎从未被调用过。例如,运行以下代码:
def del_A(name):
print('An A deleted:' + name)
class A(object):
def __init__(self, name):
print('A created')
self.name = name
self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n))
class B(object):
def __init__(self):
print('B created')
if __name__ == '__main__':
a = A('a1')
b = B()
a.other = b
b.other = a
返回:
A created
B created
删除循环引用使 lambda 回调起作用(打印“An A deleted: a1”)。用一个简单的函数调用替换 lambda 也可以,但是在初始化弱引用时参数值是固定的,而不是在调用回调时:
self._wr = weakref.ref(self, del_A(self.name))
...
a = A('a1')
a.name = 'a2'
b = B()
a.other = b
b.other = a
返回:
A created
An A deleted:a1
B created
知道为什么 lambda 回调不适用于循环引用吗?