weakref库允许pythoner创对象的弱引用。
一个对象的弱引用并不足以使得对象存在。当一个对象仅仅剩下弱引用的时候,python的垃圾回收机制会回收销毁这些对象,收回内存。
弱引用的一个主要用途就是来实现缓存或者大对象的映射。就是当其他地方没有对这些大文件的引用的时候,这个对象会被销毁。
例如,你有很多比较大的图像,你希望每个都有一个名字相关联。如果你用python中的dict类型的对象来完成名字到图像对象的映射,这些对象会一直存在着,因为其存在于字典中(有非弱引用引用这个对象)。weakref中的WeakKeyDictionary和WeakValueDictionary可以用来解决这个问题(也就是说这些大对象可以作为键或者值)。当仅有弱引用指向这些对象的时候,这些对象会被销毁,并且WeakKeyDictionary和WeakValueDictionary中对应的映射也会被删除。
其中常用的方法如下
weakref.
ref
(object[, callback]):返回一个对象的弱引用,调用返回对象(也就是r()),会返回一个该弱引用指向的对象。
weakref.
proxy
(object[, callback]):获取对象的代理,这个代理相当于原对象,也相当于一个弱引用。
weakref.
getweakrefcount
(object):返回对象的弱引用个数
weakref.getweakrefs
(object):以列表的方式返回对象的所有弱引用
weakref.
WeakKeyDictionary
([dict]):键作为弱引用
weakref.WeakValueDictionary
([dict]):值作为弱引用
weakref.
WeakSet
([elements]):弱引用的集合
关于类中定义的__weakref__:
__weakref__
is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref
(or sometimes weakproxy
) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.
It's just an implementation detail that allows the garbage collector to inform weak references that it's referent has been collected, and to not allow access to it's underlying pointer any more.
The weak reference can't rely on checking the reference count of the object it refers to. This is because that memory may have been reclaimed and now being used by another object. Best case scenario the VM will crash, worst case the weak reference will allow access to an object it wasn't originally referring to. This is why the garbage collector must inform the weak reference it's referent is no longer valid.
觉得学习需要实践,之前就知道弱引用,但是呢,一直不知道干什么的。看了官方文档有英文介绍,感觉解释清楚了弱引用的用途就给大致翻译了一下。