[英]Python attributeError on __del__
我有一個 python 類對象,我想分配一個類變量的值
class Groupclass(Workerclass):
"""worker class"""
count = 0
def __init__(self):
"""initialize time"""
Groupclass.count += 1
self.membercount = 0;
self.members = []
def __del__(self):
"""delte a worker data"""
Groupclass.count -= 1
if __name__ == "__main__":
group1 = Groupclass()
這個執行結果是正確的,但是有一條錯誤信息說:
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored
有人能告訴我我做錯了什么嗎?
您的__del__
方法假定該類在調用時仍然存在。
這個假設是不正確的。 當您的 Python 程序退出時Groupclass
已被清除,現在設置為None
。
首先測試對類的全局引用是否仍然存在:
def __del__(self):
if Groupclass:
Groupclass.count -= 1
或使用type()
獲取本地引用:
def __del__(self):
type(self).count -= 1
但注意,這意味着對於語義count
的變化,如果Groupclass
的子類(每個子類獲得一個.count
屬性與僅Groupclass
具有.count
屬性)。
引用__del__
鈎子文檔:
警告:由於調用
__del__()
方法的環境不穩定,在執行過程中發生的異常將被忽略,而是將警告打印到sys.stderr
。 此外,當__del__()
被調用以響應一個模塊被刪除時(例如,當程序執行完成時),__del__()
方法引用的其他全局變量可能已經被刪除或正在被拆除(例如進口機器關閉)。 出於這個原因,__del__()
方法應該做維護外部不變量所需的絕對最小值。 從版本 1.5 開始,Python 保證名稱以下划線開頭的全局變量在刪除其他全局變量之前從其模塊中刪除; 如果不存在對此類全局變量的其他引用,這可能有助於確保在__del__()
方法時導入的模塊仍然可用。
如果您使用的是 Python 3,則有兩個額外的注意事項適用:
CPython 3.3 自動將隨機散列鹽應用於globals
字典中使用的str
鍵; 這也會影響清除全局變量的順序,並且您可能只在某些運行中看到問題。
CPython 3.4 不再根據Safe Object Finalization將全局變量設置為None
(在大多數情況下); 參見PEP 442 。
當__del__()
方法被調用時,Groupclass 可能會被垃圾回收機制回收,所以使用 Groupclass.xxx 可能會失敗。 但是您可以通過self.__class__.count
訪問 count 變量。 代碼如下:
def __del__(self):
self.__class__.count -= 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.