Python 3.x 传递给_target()的参数数中存在TypeError
我想在python中的单独线程中运行一个方法(speak)。这是我的密码Python 3.x 传递给_target()的参数数中存在TypeError,python-3.x,multithreading,Python 3.x,Multithreading,我想在python中的单独线程中运行一个方法(speak)。这是我的密码 import threading class Example: def instruct(self, message_type): instruction_thread = threading.Thread(target=self.speak, args=message_type) instruction_thread.start() def speak(self, me
import threading
class Example:
def instruct(self, message_type):
instruction_thread = threading.Thread(target=self.speak, args=message_type)
instruction_thread.start()
def speak(self, message_type):
if message_type == 'send':
print('send the message')
elif message_type == 'inbox':
print('read the message')
e = Example()
e.instruct('send')
但我有以下错误
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\talkMail\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\ProgramData\Anaconda3\envs\talkMail\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
TypeError: speak() takes 2 positional arguments but 5 were given
这是什么原因?有人能澄清一下吗?文件:
args是目标调用的参数元组。默认为()
因此,不要像现在这样将参数作为字符串传递,而是希望将其作为元组传递,如args=(message\u type,)
一旦这样做,代码就可以正常工作
import threading
class Example:
def instruct(self, message_type):
#Pass message_type as tuple
instruction_thread = threading.Thread(target=self.speak, args=(message_type,))
instruction_thread.start()
def speak(self, message_type):
if message_type == 'send':
print('send the message')
elif message_type == 'inbox':
print('read the message')
e = Example()
e.instruct('send')
输出是
send the message
知道了。谢谢你的帮助@德维什