在一个类中,Thread.__init__(self)是如何工作的?

2024-04-30 05:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我找到了这个密码:

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

    def run (self):
        print("It's working!")
Example().start()

上面印着“它在工作!”使用另一个线程,但这是如何工作的?我找不到关于线程的任何信息。在一个类中。这和超类有关系吗?


Tags: runfromimportself密码initexampledef
2条回答

你的__init__方法是完全多余的。实际上,您正在用您自己的实现替换Thread.__init__(),您自己的实现只调用Thread.__init__()。如果你移除它,一切都不会改变:

class Example(Thread):
    def run (self):
        print("It works!")

调用Example.run()方法很简单,因为您使用^{} method启动了线程:

start()
Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

另请参见^{} documentation

run()
Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

你的__init__方法与此无关。

现在,如果您在一个Thread子类中创建了一个__init__方法,然后没有确保调用了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__没有执行。

初始化对象时调用__init__()方法。当你做-Thread.__init__(self)时,它只是调用父类__init__()方法。

如评论中所说,你可以删除它,功能应该保持不变。在您的类中,__init__()是完全多余的。

此方法在执行以下操作时调用-

Example()

Example()创建新对象时。

当对Example()对象执行-.start()操作时,将调用run()方法。这是通过^{}方法完成的,从documentation-

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.


再添加一个print语句并将Example().start()分成两行,这样您就可以清楚地理解这一点-

>>> from threading import Thread
>>> class Example(Thread):
...     def __init__(self):
...         Thread.__init__(self)
...         print("In __init__")
...     def run (self):
...         print("It's working!")
...
>>> e = Example()
In __init__
>>> e.start()
It's working!

相关问题 更多 >