首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >传递给_target()的参数数中的_target()

传递给_target()的参数数中的_target()
EN

Stack Overflow用户
提问于 2019-05-16 05:57:26
回答 1查看 17关注 0票数 1

我想在python中的一个单独线程中运行一个方法(对话)。这是我的密码

代码语言:javascript
运行
复制
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')

但我会跟随错误,

代码语言:javascript
运行
复制
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

原因是什么?有人能澄清吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-16 06:04:58

来自文档:https://docs.python.org/3/library/threading.html#threading.Thread

args是目标调用的参数元组。默认为()。

因此,与其像现在这样以字符串的形式传递参数,不如将其作为象args=(message_type,)这样的元组传递。

一旦你这样做了,代码就可以正常工作了。

代码语言:javascript
运行
复制
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')

输出是

代码语言:javascript
运行
复制
send the message
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56161667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档