2018-10-18
閱讀量:
1191
Python中錯誤的使用__del__方法
假設(shè)有一個文件mod.py中這樣使用:
import
foo
class
Bar(object):
...
def
__del__(self):
foo.cleanup(self.myhandle)
然后試圖在another_mod.py里這樣:
import
mod
mybar =
mod.Bar()
那么你會得到一個惡心的AttributeError異常。
為啥呢?這是因?yàn)椋▍⒖歼@里),當(dāng)解釋器關(guān)閉時,模塊所有的全局變量會被置為空(None)。結(jié)果便如上例所示,當(dāng)__del__被調(diào)用時,名字foo已經(jīng)被置為空了。
使用atexit.register()可以解決這個問題。如此,當(dāng)你的程序結(jié)束的時候(退出的時候),你的注冊的處理程序會在解釋器關(guān)閉之前處理。
這樣理解的話,對上面的mod.py可以做如下的修改:
import
foo
import
atexit
def
cleanup(handle):
foo.cleanup(handle)
class
Bar(object):
def
__init__(self):
...
atexit.register(cleanup, self.myhandle)






評論(0)


暫無數(shù)據(jù)
推薦帖子
0條評論
0條評論
0條評論