0
我正在瀏覽本網站http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python,我寫了完全相似的代碼。 但是在我的代碼中,一旦對象超出範圍,destructor
就會被調用。但是在上面的鏈接中提到的代碼destructor
在代碼結束後被調用。怎麼樣?按照Python中析構函數的調用順序混淆
這裏是代碼;從鏈接
代碼
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)。 – jonrsharpe