python的弱引用

来源:互联网 发布:数据库程序设计 编辑:程序博客网 时间:2024/04/30 02:47

作用:在不增加对象的引用计数个数的情况下获得对象的引用


实际中有什么用暂时还不是很清楚,以后再补充。


#coding:gbk
'''
Created on 2014年6月14日


@author: zhoucl09164
'''


class A():
    def __del__(self):
        print(hex(id(self)),' is dead!')
    
    def test(self):
        print('test')




#弱引用的对象被删除后的回调函数
#必须以弱引用的对象ref作为参数
def callback(ref):
    print(hex(id(ref)),'dead callback!')


if __name__ == '__main__':
    import sys,weakref
    a = A()
    print(sys.getrefcount(a)) #为啥一开始就是2呢?
    
    #弱引用不增加对象的refcount
    r1 = weakref.ref(a)
    r1().test()      #test
    print(r1() is a) #True
    
    r2 = weakref.ref(a)
    print(r1 is r2) #未指定不同的回调函数时,这两个弱引用是相同的,True
    print(r1() is r2() is a)#True
    
    r3 = weakref.ref(a,callback)
    print(r1 is r3)  #False
    
    #获取对象的弱引用对象个数
    print(weakref.getweakrefcount(a))  #2
    #获取对象的所有弱引用
    print(r1,r3)
    #(<weakref at 01B282D0; to 'instance' at 01B25A58>, <weakref at 01B28360; to 'instance' at 01B25A58>)
    print(weakref.getweakrefs(a)) 
    #[<weakref at 01AF82D0; to 'instance' at 01AF5A58>, <weakref at 01AF8360; to 'instance' at 01AF5A58>]
    
    del a
    #('0x1bd9360', 'dead callback!') 回调函数先被调用
    #('0x1bd5a58', ' is dead!')




#另外一种弱引用的形式
-------------------------------------------------------------------------------------------------------------
#weakref.proxy()
    
    r4 = weakref.proxy(a)
    print(r1 is r4) #False
    #print(r1() is r4()) #此句报错:TypeError: 'weakproxy' object is not callable
    r4.test() #test
    
    r5 = weakref.proxy(a,callback)
    print(r4 is r5) #False
    
    
    
0 0
原创粉丝点击