Python destructors in new and old style classes [duplicate]

感情迁移 提交于 2019-11-30 21:30:52
mgilson

The python data model explicitly states:

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

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


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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!