【问题标题】:Confusion in order of Destructor call in PythonPython中的析构函数调用顺序混乱
【发布时间】:2016-05-22 20:43:56
【问题描述】:

我正在浏览这个网站http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python,我编写了完全相同的代码。 但是在我的代码中,一旦对象超出范围,就会调用destructor。但是上面链接中提到的代码,destructor 在代码结束后被调用。怎么样?

这里是代码;

链接中的代码

class FooType(object):
    def __init__(self, id):
        self.id = id
        print self.id, 'born'

    def __del__(self):
        print self.id, 'died'

def make_foo():
    print 'Making...'
    ft = FooType(1)
    print 'Returning...'
    return ft

print 'Calling...'
ft = make_foo()
print 'End...'
Output is :
Calling...
Making...
1 born
Returning...
End...
1 died <----- Destructor called

我的代码:

abc = [1,2,3]
class myclass(object):
    def __init__(self):
        print "const"
    abc = [7,8,9]
    a = 4
    def __del__(self):
        print "Dest"
def hello():
    abc = [4,5]
    print abc
    my = myclass()
    print my.abc, my.a
    print "I am before Dest"
    return "Done"

ret = hello()
print ret
print abc

输出:

[4, 5]
const
[7, 8, 9] 4
I am before Dest
Dest<---------- Destructor
Done
[1, 2, 3]

【问题讨论】:

  • 因为当你写的最后一行被执行时程序并没有立即结束,所以还有一些整理工作要做(例如你的对象被取消引用和__del__eted)。

标签: python destructor


【解决方案1】:

因为对象是由函数返回的,所以它仍然在主程序的范围内。在您的示例中,对象永远不会离开函数,因此当函数返回时它会超出范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-08
    • 2013-06-24
    • 2011-11-24
    • 2020-04-08
    • 2012-05-22
    相关资源
    最近更新 更多