Python闭包更新外部变量时触发UnboundLocalError问题求助
嵌套函数中UnboundLocalError的原因与解决办法
错误原因
Python的作用域规则规定:如果嵌套函数内部对某个变量执行赋值操作,解释器会默认该变量是当前嵌套函数的局部变量,而非外层函数的非局部变量。
你的inc函数里的count += step本质是count = count + step,包含赋值操作,因此Python会将inc中的count标记为局部变量。但这个局部变量在赋值前并未定义,运行时就会抛出UnboundLocalError。
解决方法
方法1:使用nonlocal关键字(Python 3+)
在inc函数开头添加nonlocal count,明确告诉Python该变量属于外层嵌套函数的作用域,而非当前函数的局部变量:
def make_counter(): count = 0 def inc(step=1): nonlocal count if step > 0: count += step return count return inc c = make_counter() print(c()) # 输出1
方法2:使用可变对象(兼容Python 2)
利用可变对象(如列表、字典)的特性:修改可变对象的内部元素不属于赋值操作,不会触发局部变量判定。可以把count放在列表中存储:
def make_counter(): count = [0] def inc(step=1): if step > 0: count[0] += step return count[0] return inc c = make_counter() print(c()) # 输出1
方法3:使用类实现计数器
如果需要更清晰的状态管理逻辑,面向对象的类写法更直观:
class Counter: def __init__(self): self.count = 0 def inc(self, step=1): if step > 0: self.count += step return self.count c = Counter() print(c.inc()) # 输出1
内容的提问来源于stack exchange,提问作者rexyrzi
相关产品推荐
相关产品推荐

