Python 中 Destructor 调用的顺序混乱

Confusion in order of Destructor call in Python

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

这是代码;

代码来自 link

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]

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

时它超出范围