我以为我终于在python中获得了引用计数,直到我想出了下面的示例代码(在repl.it测试)。其结果提出了3个问题:
为什么 This
和That
以2个引用开始?
当this
被杀时,that.objects
中代理引用的this
对象应该会死亡;但方法仍然存在。那是为什么?
删除that
后,未运行gc.collect()
,似乎已收集对that
的引用;但对this
foo
方法的弱代理引用并不是。那是为什么?
提前致谢。
import sys, weakref, gc
def printf():
print 'Actual -> ', "This:", sys.getrefcount(This), ' ', 'That:', sys.getrefcount(That), '\n'
class This():
def __init__(self):
self.objects = [ self.foo ]
def foo(self):
pass
class That():
def __init__(self, **kw):
self.objects = [ weakref.proxy(kw['obj']).foo ]
#self.objects = [ kw['obj'] ]
def bar(self):
pass
print '### Before ###'
print 'Expected -> ', "This: 1", ' ', 'That: 1'
printf()
this = This(); that = That(**{'obj': this})
print '### Start Runtime ###'
print 'Expected -> ', "This: 3", ' ', 'That: 2'
printf()
del this
gc.collect()
print '### Important Event ###'
print 'Expected -> ', "This: 1", ' ', 'That: 2'
printf()
del that
print '### Secondary Event ###'
print 'Expected -> ', "This: 1", ' ', 'That: 1'
printf()