python的WeakKeyDictionary類和weakref模塊的其餘函數python
# -*- coding: utf-8 -*- # @Author : ydf # @Time : 2019/6/13 13:18 import time import weakref from app.utils_ydf import nb_print class A(): def __init__(self,x): self._x = x def __repr__(self): return f'A類的{self._x}實例 {id(self)}' def __del__(self): nb_print(f'摧毀啦 {self._x} 。。。。') wd = dict() # wd = weakref.WeakKeyDictionary() a1 = A(1) a2 = A(2) wd[a1] = 'xxxxxxx' wd[a2] = 'yyyyyyy' nb_print('銷燬a1對象前') for item in wd.items(): nb_print(item) del a1 nb_print('銷燬a1對象後') for item in wd.items(): nb_print(item)
while 1:
time.sleep(10) # 阻止退出觸發del,致使不方便觀察
使用普通dictapp
使用 weakref.WeakKeyDictionary對比使用普通字典,能夠看到不一樣的地方是銷燬a1後,普通字典中還有a1這個鍵,而且del a1時 沒法觸發A類的__del__方法,。函數
除此以外還有weakvaluedictionary和weakset這些對象。spa
weakref裏面的函數。code
class TestObj: def __init__(self): self.xx = 666 def test_func(reference): nb_print('Hello from Callback function!') nb_print(reference, 'This weak reference is no longer valid') t = TestObj() # 創建一個a的弱引用 nb_print(t.xx) t_ref = weakref.ref(t, test_func) nb_print(t_ref().xx) t.xx = 777 nb_print(t_ref().xx) del t nb_print(t_ref().xx) # 能夠發現用不了了。