为什么super(Thread, self).__init__()在threading.Thread子类中不起作用?

17 投票
1 回答
18665 浏览
提问于 2025-04-15 18:52

在Python中,我知道的每个对象都可以通过调用以下方式来处理它的基类初始化:

super(BaseClass, self).__init__()

但是,对于threading.Thread的子类来说似乎不是这样。如果我在SubClass.__init__()中尝试这样做,我会得到:

RuntimeError: thread.__init__() not called

这个错误是怎么回事?我查看了threading.Thread的源代码,发现它的__init__方法应该会设置Thread.__initialized = True。我看到所有的示例都使用了以下的__init__

class YourThread(threading.Thread):
    def __init__(self, *args):
        threading.Thread.__init__(self)
        # whatev else

但这是为什么呢?

1 个回答

43

这个方法很好用:

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

我觉得你代码里的问题是,你把基类传给了super,而不是当前的类。也就是说,你调用了super(threading.Thread, ...,这样做是不对的。因为你没有展示出出错的代码,所以很难确定具体问题,但这是我根据你用的语言推测出来的!-)

撰写回答