Why do I get "AttributeError: 'super' object has no attribute '__del__'" when calling the destructor of super from my Thread subclass' destructor?

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__'

这是为什么,如何解决?

是不允许这样显式调用super的__del__()方法,还是什么? (Google 似乎告诉我不是这样,但仍然不会给我任何答案来说明为什么会这样)

super(type(self), self) is always wrong。在 Python 2 中,您必须明确命名当前的 class,例如super(MyThread, self)。在 Python 3 中,您可以简单地使用 super():

class MyThread(threading.Thread):
    def __init__(self):
        super().__init__()
        # ...

    def run(self):
        # ...

就是说,如果 superclass 没有 __del__ 那么你会得到这个 AttributeError。如果你的基础 classes 没有 __del__ 你可以简单地忽略它。在您的 class.

中实施 __del__ 很少有充分的理由

如果您需要受控清理,请考虑使用实施 上下文管理器