weakref庫允許pythoner創(chuàng)對象的弱引用。
一個(gè)對象的弱引用并不足以使得對象存在。當(dāng)一個(gè)對象僅僅剩下弱引用的時(shí)候,python的垃圾回收機(jī)制會回收銷毀這些對象,收回內(nèi)存。
弱引用的一個(gè)主要用途就是來實(shí)現(xiàn)緩存或者大對象的映射。就是當(dāng)其他地方?jīng)]有對這些大文件的引用的時(shí)候,這個(gè)對象會被銷毀。
例如,你有很多比較大的圖像,你希望每個(gè)都有一個(gè)名字相關(guān)聯(lián)。如果你用python中的dict類型的對象來完成名字到圖像對象的映射,這些對象會一直存在著,因?yàn)槠浯嬖谟谧值渲?有非弱引用引用這個(gè)對象)。weakref中的WeakKeyDictionary和WeakValueDictionary可以用來解決這個(gè)問題(也就是說這些大對象可以作為鍵或者值)。當(dāng)僅有弱引用指向這些對象的時(shí)候,這些對象會被銷毀,并且WeakKeyDictionary和WeakValueDictionary中對應(yīng)的映射也會被刪除。
其中常用的方法如下
weakref.ref(object[, callback]):返回一個(gè)對象的弱引用,調(diào)用返回對象(也就是r()),會返回一個(gè)該弱引用指向的對象。
weakref.proxy(object[, callback]):獲取對象的代理,這個(gè)代理相當(dāng)于原對象,也相當(dāng)于一個(gè)弱引用。
weakref.getweakrefcount(object):返回對象的弱引用個(gè)數(shù)
weakref.getweakrefs(object):以列表的方式返回對象的所有弱引用
weakref.WeakKeyDictionary([dict]):鍵作為弱引用
weakref.WeakValueDictionary([dict]):值作為弱引用
weakref.WeakSet([elements]):弱引用的集合
關(guān)于類中定義的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.