首页 > 解决方案 > 传递给 _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

这是什么原因?谁能澄清一下?

标签: python-3.xmultithreading

解决方案


来自文档: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

推荐阅读