Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将元组值作为参数发送给作为线程启动的函数?_Python_Multithreading_Arguments - Fatal编程技术网

Python 如何将元组值作为参数发送给作为线程启动的函数?

Python 如何将元组值作为参数发送给作为线程启动的函数?,python,multithreading,arguments,Python,Multithreading,Arguments,我有一个类函数,我想作为线程启动。该函数将元组值作为其参数。该函数工作正常,但我的初始设置抛出一个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

我有一个类函数,我想作为线程启动。该函数将元组值作为其参数。该函数工作正常,但我的初始设置抛出一个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。我尝试过以各种方式将值打包到元组中,但无法消除错误。想法?

这看起来真的很难看,但我相信应该是
args=((2,1),
(或者
args=[(2,1)]
可能看起来稍微好一点)


args
应该是函数所有参数的元组,因此要传递元组,需要元组的元组。此外,Python要求您为具有一个元素的元组添加额外的逗号,以区别于仅用括号包装表达式。

args
获取要传递给函数的参数元组。当你说
args=(2,1)
时,你并没有告诉它用一个参数
(2,1)
调用
msg
;您告诉它使用两个参数调用它,
2
1

您需要
args=((2,1),)