新旧样式类中的Python析构函数 [英] Python destructors in new and old style classes

查看:92
本文介绍了新旧样式类中的Python析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么对象破坏在新样式类中的作用与旧样式类不同。

I'm trying to understand why object destruction works differently in new style classes compared to old style ones.

class Wrapper():
    class Inner(object):
        def __del__(self):
            print 'Inner destructor'

    innerInstance = Inner()

    def __del__(self):
        print 'Wrapper destructor'

if __name__ == '__main__':
    x = Wrapper()

在退出时,将输出:

Wrapper destructor
Inner destructor

但是,如果我使用包装器作为新样式类,仅调用包装的析构函数,并且输出为:

however, if i use Wrapper as a new style class, only the wrapper destructor is called, and the output is:

Wrapper destructor

有人可以解释上面显示的行为吗?

Could someone explain the behavior shown above ?

推荐答案

python 数据模型前明确指出:

The python data model explicitly states:


不能保证调用 __ del __()方法解释器退出时仍然存在的对象。

It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

在这种情况下,是 Wrapper (类和实例)对象在解释器退出时仍然存在,因此不能保证将其完成。并且即使我们看到包装器 实例已完成,也没有保证包装器 将最终确定(这是保存您的 Inner 实例的原因)。

In this case, a Wrapper (class and instance) object still exists when the interpreter exits, so there is no guarantee that it will be finalized. And even though we see that the Wrapper instance is finalized, there is no gurarantee that the Wrapper class will be finalized (which is what is holding your Inner instance).

另外,如果我使用Jython运行此代码,则不会为任何一个对象调用 __ del __ (无论无论我们使用的是旧样式类还是新样式类)。令人惊讶的是,如果我显式删除对象,它甚至不起作用(对于Jython)(但是此代码对CPython起作用,而不管旧样式/新样式):

As a side note, if I run this code with Jython, __del__ isn't called for either object (regardless of whether we're using old-style or new-style classes). Suprisingly, It doesn't even work (with Jython) if I explicitly delete the objects (but this code does work with CPython, regardless of old-style/new-style):

class Wrapper():
    class Inner(object):
        def __del__(self):
            print 'Inner destructor'

    innerInstance = Inner()

    def __del__(self):
        print 'Wrapper destructor'

if __name__ == '__main__':
    print "foo"
    x = Wrapper()
    print "bar"
    del x
    del Wrapper

这篇关于新旧样式类中的Python析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆