在Python2中,我使用这个简单的方法运行Thread
通过参数传递参数:
import threading
class FuncThread(threading.Thread):
'''
it worked fine in Python2
'''
def __init__(self, target, *args):
self._target = target
self._args = args
print( self._args )
threading.Thread.__init__(self)
def run(self, *args):
print( self._args )
self._target(*self._args)
def testThreading(say=''):
print("I'm a thread %s" % say)
t = FuncThread(testThreading, 'hi')
t.start()
现在在Python3里这已经不起作用了,我开始
^{pr2}$因为在run
重写中,self._args
为空。如果我在Python3中使用新语法,它就是
# this works fine in Python3
threading.Thread(target=testThreading, args=('Hello Thread!',)).start()
这很好,那么如何正确地重写run
方法?在
尝试如下:
我以前也遇到过这种情况,在对子类进行任何尝试之前初始化父类,在本例中,
FuncThread
最终被重写。在基}来达到自己的目的。因为您调用的super
threading.Thread
类使用self._target
和{__init__
没有参数,所以在父构造函数中将这些参数设置为None
。要解决此问题,只需删除您的__init__
在创建实例时使用关键字参数,并让默认行为为您完成任务:如果要保留原始构造函数签名,请使用}参数调用父
^{pr2}$target
和{__init__
,在这种情况下,您不需要自己显式地设置它们:这是Python3的解决方案:
相关问题 更多 >
编程相关推荐