鱼C论坛

 找回密码
 立即注册
查看: 1166|回复: 1

[已解决]使用Thread类创建线程函数传参无法传递类对象的问题

[复制链接]
发表于 2020-8-13 14:18:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
如题
  1. import threading

  2. def testfunc(class_name):
  3.     class_name.class_test()

  4. class Test_A():
  5.     def __init__(self):
  6.         pass
  7.     def class_test(self):
  8.         print("test")

  9. a = Test_A()

  10. test_thread = threading.Thread(target = testfunc, args = (a))
  11. test_thread.start()
复制代码


这段代码运行会报错:TypeError: testfunc() argument after * must be an iterable, not Test_A

如果我要传递一个类对象作为参数,我应该放弃这种创建线程函数的方法吗?
最佳答案
2020-8-13 14:24:45
如果元组中只有一个元素,那么末尾要加逗号

  1. import threading

  2. def testfunc(class_name):
  3.     class_name.class_test()

  4. class Test_A():
  5.     def __init__(self):
  6.         pass
  7.     def class_test(self):
  8.         print("test")

  9. a = Test_A()

  10. test_thread = threading.Thread(target = testfunc, args = (a,))
  11. test_thread.start()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-8-13 14:24:45 | 显示全部楼层    本楼为最佳答案   
如果元组中只有一个元素,那么末尾要加逗号

  1. import threading

  2. def testfunc(class_name):
  3.     class_name.class_test()

  4. class Test_A():
  5.     def __init__(self):
  6.         pass
  7.     def class_test(self):
  8.         print("test")

  9. a = Test_A()

  10. test_thread = threading.Thread(target = testfunc, args = (a,))
  11. test_thread.start()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-25 16:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表