python中的weakref庫

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.

覺得學習需要實踐,之前就知道弱引用,但是呢,一直不知道幹什麼的。看了官方文檔有英文介紹,感覺解釋清楚了弱引用的用途就給大致翻譯了一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章