class weakref.ref(object[, callback]) ,创建一个弱引用。object是被引用的对象,callback是回调函数,当引用对象被删除时,会调用回调函数
weakref.proxy(object[, callback]), 创建一个用弱引用实现的代理对象,参数同上;使用代理和使用普通weakref的区别就是不需要(),可以像原对象一样地使用proxy访问原对象的属性
例子:
- ref方法简介
# -*- coding=utf-8 -*-
import weakref
class Student(object):
def __init__(self):
self.name = 'Ricky'
def study(self):
print '{} study hard...'.format(self.name)
def weakref_callback(reference):
print 'hello from callback function!'
print reference, 'this weak reference is no longer valid'
if __name__ == '__main__':
stu = Student()
# ref方法,创建一个stu的弱引用
x = weakref.ref(stu, weakref_callback)
print x
print x()
print 'stu.name', x().name
del stu
#output:
0x7f7320e94310; to 'Student' at 0x7f7320e90a10>
<__main__.Student object at 0x7f7320e90a10>
stu.name Ricky
hello from callback function!
0x7f7320e94310; dead> this weak reference is no longer valid
# -*- coding=utf-8 -*-
import weakref
class Student(object):
def __init__(self):
self.name = 'Ricky'
def study(self):
print '{} study hard...'.format(self.name)
def weakref_callback(reference):
print 'hello from callback function!'
# print reference, 'this weak reference is no longer valid'
print 'reference', reference # 使用proxy,reference打印出的是一句exception信息
if __name__ == '__main__':
stu = Student()
# ref方法,创建一个stu的弱引用
x = weakref.proxy(stu, weakref_callback)
print x
print 'stu.name', x.name
# output:
<__main__.Student object at 0x7f4dcf480550>
stu.name Ricky
hello from callback function!
Exception ReferenceError: 'weakly-referenced object no longer exists' in 0x7f4dcf481140> ignored
reference
# -*- coding=utf-8 -*-
import weakref
class Student(object):
def __init__(self):
self.name = 'Ricky'
def study(self):
print '{} study hard...'.format(self.name)
if __name__ == '__main__':
stu = Student()
print 'getweakrefs', weakref.getweakrefs(stu)
print 'WeakKeyDictionary', weakref.WeakKeyDictionary({stu: 'aa'})
print 'WeakKeyDictionary', weakref.WeakValueDictionary({'aa': stu})
print 'WeakSet', weakref.WeakSet([stu])
print 'ReferenceType', weakref.ReferenceType
print 'ProxyType', weakref.ProxyType
#输出
getweakrefs []
WeakKeyDictionary 140098833786280>
WeakKeyDictionary 140098833786280>
WeakSet <_weakrefset.WeakSet object at 0x7f6b4d38ddd0>
ReferenceType 'weakref'>
ProxyType 'weakproxy'>