[英]Why do I get “AttributeError: 'super' object has no attribute '__del__'” when calling the destructor of super from my Thread subclass' destructor?
在我的Python(3.6)程序中,我有一個線程對象,如下所示:
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
...
def __del__(self):
...
super(type(self), self).__del__()
def run(self):
...
在主程序中這樣使用:
def main():
my_thread = MyThread()
my_thread.start()
...
my_thread.join()
但是,一旦我嘗試運行該程序,就會發生以下Python崩潰:
Exception ignored in: <bound method MyThread.__del__ of <MyThread(Thread-6, stopped 1234)>>
Traceback (most recent call last):
File "c:/my_proj/my_program.py", line 123, in __del__
super(type(self), self).__del__()
AttributeError: 'super' object has no attribute '__del__'
為什么會這樣,如何解決?
這樣不允許顯式調用__del__()
方法嗎? (Google似乎告訴了我其他方式,但仍然無法提供任何答案說明這種情況的發生)
super(type(self), self)
總是錯誤的 。 在Python 2中,必須顯式命名當前類,例如super(MyThread, self)
。 在Python 3中,您可以簡單地使用super()
:
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
# ...
def run(self):
# ...
也就是說,如果超類沒有__del__
那么您將得到此AttributeError
。 如果您的基類沒有__del__
,則可以忽略它。 在您的課程中很少有理由實現__del__
。
如果需要受控清理,請考慮使用實現上下文管理器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.