【问题标题】:_thread a function inside class returned "TypeError: func_one() takes 2 positional arguments but 3 were given"_thread 类内的函数返回“TypeError:func_one() 接受 2 个位置参数,但给出了 3 个”
【发布时间】:2020-07-25 21:45:36
【问题描述】:
import _thread
class cl:

    def func_one(self, conn):
        ...

    def func_two(self):
        str_key = "ABC"
        _thread.start_new_thread(self.func_one, (self,str_key))

一旦解释,它就会返回以下内容:

TypeError: func_one() takes 2 positional arguments but 3 were given

我尝试过不带 self 的线程 func_one()。一开始是 (self.func_one()) 但后来它返回

NameError: name 'func_one' is not defined

如果我想从 func_two() 线程化 func_one() 应该怎么做?它们属于同一个类 cl()。

我使用以下方法调用 func_two():

if(__name__ == "__main__"):

  c = cl()
  c.func_two()

更新:

我找到了解决问题的方法:

import _thread
class cl:

    def func_one(self, conn, tmp):
        ...

    def func_two(self):
        str_key = "ABC"
        _thread.start_new_thread(self.func_one, (str_key,None))
    

【问题讨论】:

    标签: python python-3.x typeerror python-multithreading nameerror


    【解决方案1】:

    当您调用 _thread.start_new_thread(self.func_one, (self,str_key)) 时,您调用了两次 self,一次是添加函数指针,第二次是作为参数。

    func_one 正在接收 self, self, str_key 作为参数,而它期待 self, str_keys

    删除括号内的self后应该可以工作,如下所示:

    _thread.start_new_thread(self.func_one, (str_key))

    【讨论】:

    • _thread.start_new_thread(self.func_one, (str_key)) return 'TypeError: 2nd arg must be a tuple'
    • str_key后面加一个逗号,就是(str_key,)
    猜你喜欢
    • 2022-01-17
    • 2019-09-21
    • 2019-07-19
    • 2021-02-02
    • 2020-02-07
    • 2017-03-14
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多