You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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")

说明

  1. 给线程类的__init__方法添加color参数,接收外部函数传入的值并绑定到实例的self.color属性上
  2. run方法必须添加self参数,这样才能访问实例上的color属性
  3. 原代码仅定义了线程类,没有创建实例和启动线程,补充这部分逻辑才能让代码正常运行

内容的提问来源于stack exchange,提问作者PCG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:07:08