类中的Thread .__ init __(self)如何工作?

Mau*_*rst 2 python multithreading

所以我找到了这段代码:

from threading import Thread
class Example(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run (self):
        print("It's working!")
Example().start()
Run Code Online (Sandbox Code Playgroud)

并显示“正在运行!” 使用另一个线程,但这如何工作?我在类中找不到有关Thread .__ init __(self)的任何信息。它和超类有关吗?

Mar*_*ers 6

您的__init__方法是完全多余的。实际上Thread.__init__(),您将替换为自己的实现,而您自己的实现只需调用即可Thread.__init__()。如果删除它,则什么都不会改变:

class Example(Thread):
    def run (self):
        print("It works!")
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

因为这是一个常见错误,所以该Thread.start方法将引发一个自定义异常,以明确告诉您Thread.__init__尚未执行。