我正在尝试存储一些方法回调,但引用它会使绑定的对象保持活动状态,所以我试图为方法保留一个弱引用,但这似乎不可能?
所以
为什么我不能保持弱参考。to 方法(见下面的例子)
保持方法参考的最佳方法是什么?标准库中有什么东西吗?否则我将不得不保留函数和对象引用。分离?
例子:
import weakref
class A(object):
def m(self): pass
a = A()
import weakref
class A(object):
def m(self): pass
a = A()
rm = weakref.ref(a.m)
print "is weak ref to method dead?",rm() is None
print "Q1. why can't i keep weakref to bound method?"
ra = weakref.ref(a)
m = a.m
print "delete object"
del a
print "is object dead?",ra() is None
print "delete method"
del m
print "is object dead?",ra() is None
print "Q2. hmmm so i am stuck i can't keep a ref as it stops the object from gc, but weakref to method isn't working?"