UnboundLocalError求助:嵌套线程类无法访问外部函数参数
解决Python线程类访问外部函数参数的作用域问题
原问题代码
import threading def showColor(color = "Green"): class loading(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(): c = '>'+color+'<' print(c) showColor("Red")
报错信息
cannot access local variable 'color' where it is not associated with a value
解决方案
问题根源有两个:一是run方法缺少self参数,无法作为线程实例的方法正常执行;二是线程类内部无法直接捕获外部函数的color变量。可以通过将参数传递给线程类实例并保存为属性的方式解决,无需手动硬编码内部值:
import threading def showColor(color = "Green"): class loading(threading.Thread): def __init__(self, color): super().__init__() self.color = color # 将外部传入的color保存为实例属性 def run(self): # 必须带self参数,作为实例方法 c = '>'+self.color+'<' print(c) # 创建线程实例并启动执行 thread = loading(color) thread.start() thread.join() # 可选,等待线程执行完毕再继续主程序 showColor("Red")
说明
- 给线程类的
__init__方法添加color参数,接收外部函数传入的值并绑定到实例的self.color属性上 run方法必须添加self参数,这样才能访问实例上的color属性- 原代码仅定义了线程类,没有创建实例和启动线程,补充这部分逻辑才能让代码正常运行
内容的提问来源于stack exchange,提问作者PCG
相关产品推荐
相关产品推荐

