我有一个类函数,想将其作为线程启动。该函数以元组值作为参数。该函数可以正常工作,但我的初始设置会抛出TypeError。以下是一些示例代码:
import threading
class Test:
def __init__(self):
t = threading.Thread(target=self.msg, args=(2,1))
t.start()
print "started thread"
# msg takes a tuple as its arg (e.g. tupleval = (0,1))
def msg(self,tupleval):
if(tupleval[0] > 1):
print "yes"
else:
print "no"
test = Test()
test.msg((2,2))
test.msg((0,0))
然后输出结果如下:
started thread
yes
no
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: msg() takes exactly 2 arguments (3 given)
看起来这对最后两个显式调用有效,但是初始设置调用会抛出TypeError。我尝试过以各种方式将值打包成元组,但无法摆脱错误。有什么想法吗?