python-3.x - 传递给 _target() 的参数数量中的类型错误
问题描述
我想在 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
这是什么原因?谁能澄清一下?
解决方案
来自文档: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
推荐阅读
- python - 如何迭代列表一次访问两个索引并在每次迭代后移动一个索引时间?
- json - 针对动态数据进行验证 - JSON Schema - Ajv
- flutter - 创建一个具有两个圆角和两个直切角的 Flutter TextFormField
- android - 如何保存对象的 ArrayList?
- php - 使用 circleci/php:7.3-cli-node-browsers 构建 docker 镜像
- mongodb - 如何使用新的 MongoDB Shell (mongosh) 获取未截断的不同值列表
- react-native - 如何在组件挂载后聚焦 TextInput(以 TextInput 为中心进行初始化) - React Native
- reactjs - 如何在 useEffect 中使用自定义挂钩?
- python - 如何加快对数百万条记录的 Spotipy API 调用?
- nativescript - ios 的 Nativescript 构建成功但收到错误消息