Python 闭包混乱

Python closure confusion

我在 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

注意:如果您正在使用Python2.x,请遵循this question

中提到的任何方法