how to send a tuple value as an arg to a function started as a thread?
I have a class function that I want to start up as a thread. The function takes as its argument a tuple value. The function works fine but my initial setup throws a TypeError. Here's some sample code:
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))
and then the output is as follows:
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, **sel开发者_如何学JAVAf.__kwargs)
TypeError: msg() takes exactly 2 arguments (3 given)
It appears to work for the two explicit calls at the end, but the initial setup call throws the TypeError. I've tried packing values into a tuple in all sorts of ways but can't get rid of the error. Ideas?
args
takes a tuple of arguments to pass to the function. When you say args=(2,1)
you're not telling it to call msg
with a single argument (2,1)
; you're telling it to call it with two arguments, 2
and 1
.
You want args=((2,1),)
.
This is going to look really ugly, but I believe it should be args=((2,1),)
(or args=[(2,1)]
might look slightly nicer).
args
is supposed to be a tuple of all the arguments to the function, so to pass a tuple, you need a tuple of a tuple. In addition, Python requires you to add the extra comma for a tuple with one element to differentiate it from just wrapping an expression with parentheses.
精彩评论