鉴于 Python documentation对于 Thread.run()
:
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.
我已经构建了以下代码:
class DestinationThread(threading.Thread):
def run(self, name, config):
print 'In thread'
thread = DestinationThread(args = (destination_name, destination_config))
thread.start()
但是当我执行它时,我收到以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
self.run()
TypeError: run() takes exactly 3 arguments (1 given)
我似乎遗漏了一些明显的东西,但我看到的各种例子都适用于这种方法。最终,我试图将字符串和字典传递到线程中,如果构造函数不是正确的方法,而是在启动线程之前创建一个新函数来设置值,我对此持开放态度。
关于如何最好地完成此任务的任何建议?
最佳答案
你真的不需要子类化 Thread。 API 支持这一点的唯一原因是为了让来自 Java 的人更舒服,这是做到这一点的唯一方法。
我们推荐您使用的模式是将方法传递给 Thread 构造函数,然后调用 .start()
。
def myfunc(arg1, arg2):
print 'In thread'
print 'args are', arg1, arg2
thread = Thread(target=myfunc, args=(destination_name, destination_config))
thread.start()
关于python - 覆盖python threading.Thread.run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660961/