重写python threading.Thread.run()

发布于 2021-01-29 19:12:25

鉴于Python文档Thread.run()

您可以在子类中重写此方法。标准的run()方法调用传递到对象构造函数的可调用对象作为目标参数(如果有),并分别从args和kwargs参数中获取顺序和关键字参数。

我构造了以下代码:

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)

似乎我缺少明显的东西,但是我看到的各种示例都可以使用此方法。最终,我尝试将字符串和字典传递给线程,如果构造方法不是正确的方法,而是在启动线程之前创建了一个新函数来设置值,那我很乐意。

关于如何最好地做到这一点的任何建议?

关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您确实不需要继承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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看