weakref庫允許pythoner創(chuàng)對象的弱引用。
一個對象的弱引用并不足以使得對象存在酒繁。當一個對象僅僅剩下弱引用的時候,python的垃圾回收機制會回收銷毀這些對象,收回內(nèi)存艳汽。
弱引用的一個主要用途就是來實現(xiàn)緩存或者大對象的映射。就是當其他地方?jīng)]有對這些大文件的引用的時候对雪,這個對象會被銷毀河狐。
例如,你有很多比較大的圖像瑟捣,你希望每個都有一個名字相關聯(lián)馋艺。如果你用python中的dict類型的對象來完成名字到圖像對象的映射,這些對象會一直存在著迈套,因為其存在于字典中(有非弱引用引用這個對象)捐祠。weakref中的WeakKeyDictionary和WeakValueDictionary可以用來解決這個問題(也就是說這些大對象可以作為鍵或者值)。當僅有弱引用指向這些對象的時候桑李,這些對象會被銷毀踱蛀,并且WeakKeyDictionary和WeakValueDictionary中對應的映射也會被刪除。
其中常用的方法如下
weakref.ref(object[, callback]):返回一個對象的弱引用贵白,調(diào)用返回對象(也就是r())率拒,會返回一個該弱引用指向的對象。
weakref.proxy(object[, callback]):獲取對象的代理禁荒,這個代理相當于原對象猬膨,也相當于一個弱引用。
weakref.getweakrefcount(object):返回對象的弱引用個數(shù)
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.