首页 > 这段Python代码哪里存在循环引用啊?

这段Python代码哪里存在循环引用啊?

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

[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.
>>> 

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

【热门文章】
【热门文章】