我正在嘗試爲具有循環引用的Python類編寫終結器。我發現弱參考回調是way to go。不幸的是,似乎我用作回調的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
卸下循環引用使得拉姆達回調作品( '的甲刪除:A1' 被打印)。通過簡單的函數調用更換拉姆達工作過,但參數值是固定的初始化時弱引用,而不是調用回調時:
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回調不適用於循環引用?
感謝您的回覆,但我相信它不能回答我的問題。我使用弱引用來避免__del__方法。 – Barthelemy 2010-02-25 12:18:20