【问题标题】:Why do circular references prevent the destructors of objects that aren't on the loop?为什么循环引用会阻止不在循环中的对象的析构函数?
【发布时间】:2013-01-15 16:33:51
【问题描述】:

在这个例子中:

class Foo(object):
    def __del__(self):
        print "Foo died"

class Bar(object):
    def __init__(self):
        self.foo = Foo()
        self.baz = Baz(self)

class Baz(object):
    def __init__(self, bar):
        self.bar = bar

b = Bar()

我希望尽管 Bar 和 Baz 之间存在循环,但仍会调用 Foo 析构函数,因为 Foo 没有对收集它们的任何 bar 或 baz 的引用,并且在收集 Foo 之前减少引用计数应该是完全安全的。为什么 python 不这样做呢?如果可以防止析构函数被其他类的完全不相关的操作调用,那么析构函数怎么可能有用?

【问题讨论】:

  • foo被引用为什么会被删除?
  • 简单回答:析构函数没用。
  • @LevLevitsky 一旦 b 超出范围(即程序结束时),它就不再被引用。试试这个例子,注释掉 self.baz 行,你会看到析构函数被调用。
  • @DanielRoseman 但它们是安全处理某些清理情况的唯一方法……上下文管理器不能跨线程工作。据我所知,这个用例可能是安全的!

标签: python garbage-collection destructor


【解决方案1】:

注意析构函数does not need to be called when the interpreter exits

快速修改您的脚本,一切如您所愿:

class Foo(object):
    def __del__(self):
        print "Foo died"

class Bar(object):
    def __init__(self):
        self.foo = Foo()
        self.baz = Baz(self)

class Baz(object):
    def __init__(self, bar):
        self.bar = bar

b = Bar()

del b

【讨论】:

  • 哦!好吧,现在我觉得自己很笨。我认为它与没有self.baz 行时的工作方式相同。谢谢,将在时间限制结束时标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 2021-08-12
  • 2016-04-21
  • 1970-01-01
  • 2012-11-07
  • 2013-04-13
相关资源
最近更新 更多