如何将call_back函数传递给这些字典?因此,如果有任何对象被垃圾回收,则会调用该函数。
import weakref
def call_back():
print("call back function called")
we_dict_demo = weakref.WeakKeyDictionary()
或
we_dict_demo = weakref.WeakValDictionary()
答案 0 :(得分:0)
我认为它没有实际意义,但是尝试尝试很有趣:
import weakref
def callback(elem):
print(elem, "gc'ed!")
# After reading lib/weakref.py it's clear what
# WeakKeyDictionary pushes as callback self._remove,
# which constructed in __init__, so let's redefine it
class MyWeakKeyDict(weakref.WeakKeyDictionary):
def __init__(self, cb, dict=None):
super().__init__(dict)
self.cb = cb
def new_remove(el, selfref=weakref.ref(self)):
self = selfref()
if self is not None:
self.cb(el)
self._old_remove(el)
self._old_remove = self._remove
self._remove = new_remove
class C:
pass
c = C()
#d = weakref.WeakKeyDictionary()
# Use our class instead of WeakKeyDictionary
d = MyWeakKeyDict(callback)
d[c] = 0
print('Before gc', list(d.items()))
del c
print('After gc', list(d.items()))
结果是
Before gc [(<__main__.C object at 0x000002690F53A588>, 0)]
<weakref at 0x000002690F54A728; dead> gc'ed!
After gc []