假設我有可能消耗的內存相當一些非常大的Python類。這個類有一些方法,負責清理一些東西在翻譯時退出,並獲取與atexit對模塊註冊:在Python中使用atexit註冊實例方法有什麼意義?
import atexit
import os
class ReallyBigClass(object):
def __init__(self, cache_file):
self.cache_file = open(cache_file)
self.data = <some large chunk of data>
atexit.register(self.cleanup)
<insert other methods for manipulating self.data>
def cleanup(self):
os.remove(self.cache_file)
這個類的各種實例可能來來去去,整個程序的壽命。我的問題是:
是使用atexit如果安全我,說,del
我所有的其他的實例引用註冊實例方法?換句話說,atexit.register()
是否像傳統綁定一樣增加引用計數器?如果是這樣,那麼現在整個類實例是否必須在內存中閒逛並等到退出,因爲它的一個方法已經用atexit註冊了,或者實例的一部分可以被垃圾回收?在類似這樣的臨時類實例的出口處構造這種清理的首選方式是什麼,以便垃圾收集可以有效地發生?