python 为什么 super(Thread, self).__init__() 不适用于 threading.Thread 子类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2197563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?
提问by Carl G
Every object I know of in Python can take care of its base class initialization by calling:
我在 Python 中知道的每个对象都可以通过调用来处理其基类初始化:
super(BaseClass, self).__init__()
This doesn't seem to be the case with a subclass of threading.Thread
, since if I try this in SubClass.__init__()
, I get:
的子类似乎不是这种情况threading.Thread
,因为如果我在 中尝试这个SubClass.__init__()
,我会得到:
RuntimeError: thread.__init__() not called
What gives this error? I looked at the source for threading.Thread
and it looks like that __init__
method should set Thread.__initialized = True
. I see that all examples use the following __init__
:
是什么导致了这个错误?我查看了源代码,threading.Thread
看起来该__init__
方法应该设置Thread.__initialized = True
. 我看到所有示例都使用以下内容__init__
:
class YourThread(threading.Thread):
def __init__(self, *args):
threading.Thread.__init__(self)
# whatev else
But why?
但为什么?
回答by Alex Martelli
This works fine:
这工作正常:
>>> class MyThread(threading.Thread):
... def __init__(self):
... super(MyThread, self).__init__()
I think your code's bug is that you're passing the baseclass, rather than the currentclass, to super
-- i.e. you're calling super(threading.Thread, ...
, and that's just wrong. Hard to say since you don't show your failing code, but that's what I infer obliquely from the language you're using!-)
我认为您的代码的错误在于您将基类而不是当前类传递给super
- 即您正在调用super(threading.Thread, ...
,这是错误的。很难说,因为你没有展示你失败的代码,但这就是我从你使用的语言中间接推断出来的!-)