Python使用_thread时报错first arg must be callable解决方法问询
报错原因
_thread.start_new_thread要求第一个参数必须是可调用的函数/方法对象,你代码中传入的self.sell(do)是方法执行语句,会直接运行sell方法并将返回值(默认是None)作为参数传入,不符合要求,因此触发「first arg must be callable」报错。
额外语法问题
除了线程传参错误外,你的代码还存在其他语法问题需要修正:
- 类定义中不能直接使用
self声明属性,self仅在实例方法内部可用,实例属性需要放到构造方法__init__中初始化 run方法中用到的do变量未提前定义,sell方法内部的do something属于无效语法- 主线程如果提前退出会导致子线程直接被终止,需要添加简单的阻塞逻辑保证子线程执行完成
解决代码
import _thread class Main(): def __init__(self): self.o = 0 def sell(self, do): # 这里替换为你的实际业务逻辑 print(f"sell方法执行,参数do为{do}") def run(self): # 按你的业务需求给do赋值即可 do = "业务参数" try: # 第一个参数传方法本身,第二个参数为传递给方法的参数元组 _thread.start_new_thread(self.sell, (do,)) except Exception as e: print(e) # 阻塞主线程,防止子线程未执行就退出 input() if __name__ == '__main__': main = Main() main.run()
内容的提问来源于stack exchange,提问作者Esteban G. Gutierrez
相关产品推荐
相关产品推荐

