在我的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__'
这是为什么,如何解决?
是不是不允许像这样显式调用super的
__del__()
方法,还是什么? (谷歌似乎告诉我不然,但仍然不会给我任何答案为什么会发生这种情况)
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__
。
如果您需要受控清理,请考虑使用实现上下文管理器。
我收到属性错误,因为我在调用要覆盖的原始方法的方法之前没有使用@api.model。