我想在python中的一个单独线程中运行一个方法(对话)。这是我的密码
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
原因是什么?有人能澄清吗?
发布于 2019-05-16 06:04:58
来自文档:https://docs.python.org/3/library/threading.html#threading.Thread
args是目标调用的参数元组。默认为()。
因此,与其像现在这样以字符串的形式传递参数,不如将其作为象args=(message_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
https://stackoverflow.com/questions/56161667
复制相似问题