类中的Thread .__ init __(self)如何工作?
所以我找到了这段代码:
from threading import Thread
class Example(Thread):
def __init__(self):
Thread.__init__(self)
def run (self):
print("It's working!")
Example().start()
并显示“正在运行!” 使用另一个线程,但这如何工作?我在类中找不到有关Thread . init (self)的任何信息。它和超类有关吗?
-
您的
__init__
方法是完全多余的。您实际上是在替换Thread.__init__()
自己的实现,而您自己的实现只需调用即可Thread.__init__()
。如果删除它,则什么都不会改变:class Example(Thread): def run (self): print("It works!")
Example.run()
之所以简称您的方法,是因为您使用Thread.start()
方法启动了线程:start()
启动线程的活动。每个线程对象最多只能调用一次。它安排
run()
在单独的控制线程中调用对象的方法。另请参阅
Thread.run()
文档:run()
表示线程活动的方法。您可以在子类中重写此方法。标准
run()
方法调用传递给对象构造函数的可调用对象作为目标参数(如果有),并分别从args和kwargs参数中获取顺序参数和关键字参数。您的
__init__
方法与此无关。现在,如果你创建了
__init__
一个方法Thread
子类,当时也 不能
确保Thread.__init__
被调用,然后你设置的重要实例的信息,打破实例防止类:>>> from threading import Thread >>> class Example(Thread): ... def run (self): ... print("It works!") ... >>> Example().start() It works! >>> class BrokenExample(Thread): ... def __init__(self): ... # not doing anything ... pass ... def run (self): ... print("It works!") ... >>> BrokenExample().start() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../lib/python2.7/threading.py", line 737, in start raise RuntimeError("thread.__init__() not called") RuntimeError: thread.__init__() not called
因为这是一个常见错误,所以该
Thread.start
方法将引发一个自定义异常,以明确告诉您Thread.__init__
未执行。