如果两个类互相引用将导致无法被正常回收,所以采取这种形式:
python
from weakref import ref
class D(object):
def __init__(self, name):
self.name = name
def __del__(self):
print('[deleted]: %s' % self.name)
class T(D):
property
def pointer(self):
return getattr(self, '_pointer', lambda: None)()
pointer.setter
def pointer(self, value):
self._pointer = ref(value)
def fn():
t, d = T('t'), D('d')
t.pointer, d.pointer = d, t
if __name__ == '__main__':
fn()
print('end')
在itchat中主要解决这样两个问题:
你需要对照该版本和前版本的结果比较差别。
python
from weakref import ref
from itchat.storage import templates
def fn():
chatroom = templates.Chatroom()
chatroom.memberList.append({})
m = chatroom.memberList[0]
return ref(m), ref(chatroom)
if __name__ == '__main__':
a, b = fn()
print(a(), b())
python
from weakref import ref
from itchat import Core
def fn():
r = Core()
return ref(r)
r = fn()
print(r())