素材牛VIP会员
这段Python代码哪里存在循环引用啊?
 街***铃  分类:Python  人气:1016  回帖:1  发布于6年前 收藏

下面的代码,gc提示说有四个无法回收(uncollectable)的对象,应该是有循环引用存在,哪里存在循环引用啊,请高人指点。这里是作者的原文 Python中带有显式del方法的对象需要手动释放循环引用

[file.py]
class Foo(object):
    def __init__(self):
        self._bar = {"test": self.test}
        print "construct"

    def test(self):
        print "test"

    def __del__(self):
        print "del"

import gc
gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_LEAK)
f = Foo()
del f
gc.collect()

执行上面代码,结果如下
>>> 
construct
gc: collecting generation 2...
gc: objects in each generation: 620 1106 8289
gc: uncollectable <Foo 02699770>
gc: uncollectable <dict 02693660>
gc: uncollectable <dict 02693540>
gc: uncollectable <instancemethod 02669198>
gc: done, 4 unreachable, 4 uncollectable, 0.0260s elapsed.
>>> 

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv6 码匠
马***0 软件测试工程师 6年前#1

一个 dict {"test": self.test } 持有 f,同时 f 也持有这个 dict,就是循环引用了。

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取