绑定方法保留对它们所属对象的引用(否则,它们无法填充self
,参见Python 文档)。考虑以下代码:
import gc
class SomeLargeObject(object):
def on_foo(self): pass
slo = SomeLargeObject()
callbacks = [slo.on_foo]
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
del slo
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
callbacks = []
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
输出:
[<__main__.SomeLargeObject object at 0x15001d0>]
[<__main__.SomeLargeObject object at 0x15001d0>]
[]
在回调中保留弱引用时要知道的一件重要事情是,您不能直接绑定弱引用方法,因为它们总是动态创建的:
>>> class SomeLargeObject(object):
... def on_foo(self): pass
>>> import weakref
>>> def report(o):
... print "about to collect"
>>> slo = SomeLargeObject()
>>> #second argument: function that is called when weakref'ed object is finalized
>>> weakref.proxy(slo.on_foo, report)
about to collect
<weakproxy at 0x7f9abd3be208 to NoneType at 0x72ecc0>