真的环,真的回收器
用真 Python 看引用环:两个对象互相引用、外面的名字都删掉,弱引用还活着吗?gc.collect() 之后呢?(弱引用不计数,对象没了它就变成 None;列表不能被弱引用,所以用一个小类)
import gc, weakref
class Node:
pass
a = Node()
b = Node()
a.other = b
b.other = a
r = weakref.ref(a)
del a, b
alive_after_del = r() is not None
gc.collect()
alive_after_gc = r() is not None
c = Node()
r2 = weakref.ref(c)
del c
print(str(alive_after_del) + "/" + str(alive_after_gc) + "/" + str(r2() is not None))
全部评论