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
- python的弱引用
- python的引用计数
- Python的引用计数器
- python的对象引用
- Python引用的理解
- python 引用,拷贝,对象回收,弱引用
- python中引用的问题
- python 的跨包引用
- python中的类的引用
- python脚本之间的引用
- python对象引用的问题
- python的对象及引用
- python循环引用的解决办法
- python循环引用的解决办法
- python参数的引用传递
- Python 引用Java 的方法
- Python中函数库的引用--Python(9)
- 弱引用,软引用,幽灵的引用
- Silverlight中定义布局面板
- 树状数组基本操作
- i2c
- 一个测试SQL2005连接的Java程序
- 石子合并问题(动态规划)
- python的弱引用
- POJ 3259 Wormholes (Bellman)
- OpenGL绘图的基本过程是:清除缓冲区,设置当前颜色,绘制几何图元,输出图形。
- DHCP协议和dhcpcd源码分析
- 聚类算法K-Means, K-Medoids, GMM, Spectral clustering,Ncut
- NOJ [1015] 一个简单的问题
- uva 457 Linear Cellular Automata(模拟)
- 浅谈IM软件如何建立安全socket连接、登录
- php 模拟登陆