我正在使用 Python 中的闭包,但我不明白为什么以下内容不起作用以及如何使其起作用:
>>> def make_counter():
... i = 0
... def inner():
... i += 1
... return i
... return inner
...
>>> c = make_counter()
>>> c()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in inner
UnboundLocalError: local variable 'i' referenced before assignment
有人可以解释一下吗? 谢谢。
最佳答案
在inner
函数中,语句
i += 1
可以这么理解
i = i + 1
由于您在此函数中为 i
赋值,Python 认为您正在创建一个作用域为当前函数的新变量。然后,当它执行右侧表达式i + 1
时,它发现i
在使用之前尚未被分配任何值。这就是它抛出的原因
UnboundLocalError: local variable 'i' referenced before assignment
要解决此问题,您需要明确告诉 Python 您没有创建新变量,而是从外部作用域访问变量,如 nonlocal
(Python 3.x)像这样
>>> def make_counter():
... i = 0
... def inner():
... nonlocal i
... i += 1
... return i
... return inner
...
>>>
>>> make_counter()()
1
注意:如果您使用的是 Python 2.x,请遵循 this question 中提到的任何方法。
关于Python 闭包困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068946/