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.
>>> 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
你的
__init__
方法是完全多余的。实际上,您正在用您自己的实现替换Thread.__init__()
,您自己的实现只调用Thread.__init__()
。如果你移除它,一切都不会改变:调用} method 启动了线程:
Example.run()
方法很简单,因为您使用^{另请参见^{} documentation :
你的
__init__
方法与此无关。现在,如果您在一个
Thread
子类中创建了一个__init__
方法,然后没有确保调用了Thread.__init__
,那么您就阻止了该类设置重要的实例信息,中断了实例:因为这是一个常见的错误,所以
Thread.start
方法抛出一个自定义异常,显式地告诉您Thread.__init__
没有执行。初始化对象时调用
__init__()
方法。当你做-Thread.__init__(self)
时,它只是调用父类__init__()
方法。如评论中所说,你可以删除它,功能应该保持不变。在您的类中,
__init__()
是完全多余的。此方法在执行以下操作时调用-
为
Example()
创建新对象时。当对} 方法完成的,从documentation-
Example()
对象执行-.start()
操作时,将调用run()
方法。这是通过^{再添加一个print语句并将
Example().start()
分成两行,这样您就可以清楚地理解这一点-相关问题 更多 >
编程相关推荐