我正在浏览这个网站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]
答案 0 :(得分:2)
因为该对象是由函数返回的,所以它仍然在主程序的范围内。在您的示例中,对象永远不会离开函数,因此在函数返回时它会超出范围。