當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python weakref.WeakMethod用法及代碼示例

用法:

class weakref.WeakMethod(method)

一個自定義 ref 子類,它模擬對綁定方法的弱引用(即,在類上定義並在實例上查找的方法)。由於綁定方法是短暫的,標準的弱引用無法保持它。 WeakMethod 有特殊代碼來重新創建綁定方法,直到對象或原始函數死亡:

>>> class C:
...     def method(self):
...         print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>

3.4 版中的新函數。

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 weakref.WeakMethod。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。