python2.7 - 这段Python代码哪里存在循环引用啊?
巴扎黑
巴扎黑 2017-04-17 14:35:52
[Python讨论组]

下面的代码,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)
阿神

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号