バインドされたメソッドは、それらが属するオブジェクトへの参照を保持します(そうでない場合、Pythonのドキュメントself
を参照して埋めることはできません)。次のコードを検討してください。
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>]
[]
コールバックでweakrefsを保持するときに知っておくべき重要なことの1つは、weakrefバインドされたメソッドは常にオンザフライで作成されるため、直接weakrefバインドすることはできないということです。
>>> 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>