我想在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
这是什么原因?有人可以澄清吗?
答案 0 :(得分:0)
从文档中: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