真的环,真的回收器

👁️ 3 人浏览 💬 0 人评论 ❤️ 添加收藏

用真 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))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论