这些额外的参考来自哪里?

时间:2014-04-30 20:35:11

标签: python reference-counting

我以为我终于在python中获得了引用计数,直到我想出了下面的示例代码(在repl.it测试)。其结果提出了3个问题:

  1. 为什么ThisThat以2个引用开始?

  2. this被杀时,that.objects中代理引用的this对象应该会死亡;但方法仍然存在。那是为什么?

  3. 删除that后,未运行gc.collect(),似乎已收集对that的引用;但对this foo方法的弱代理引用并不是。那是为什么?

  4. 提前致谢。

    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()
    

0 个答案:

没有答案