主要类:
-
WeakKeyDictionary
-
WeakValueDictionary
作用:
WeakKeyDictionary用于存储key-value, 当key消失时,则该条记录消失。
WeakValueDictionary用于存储key-value, 当value消失时,则该条记录消失。
举一个例子:
import weakref
class Test:
pass
ta = Test()
tb = Test()
# key弱引用,key不存在时,则删除该key
adict = weakref.WeakKeyDictionary()
adict[ta] = 'test_value'
del ta
print(dict(adict))
# value弱引用, value不存在时,则删除该key
bdict = weakref.WeakValueDictionary()
bdict['test_key'] = tb
del tb
print(dict(bdict))
错误例子:
import weakref
class Test:
pass
ta = Test()
tc = Test()
# 如果删除的是value,则该key仍然存在
adict = weakref.WeakKeyDictionary()
adict[ta] = tc
del tc
print(dict(adict))