嵌套函数中的奇怪作用域
Strange Scoping in Nested Functions
我有两个嵌套的 python 函数,它们看起来像这样:
def outer():
t = 0
def inner():
t += 1
print(t)
inner()
尝试调用 outer
导致以下错误:
>>> outer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sally.py", line 6, in outer
inner()
File "sally.py", line 4, in inner
t += 1
UnboundLocalError: local variable 't' referenced before assignment
我认为在 t += 1
之前添加行 global t
会有所帮助,但事实并非如此。
为什么会这样?除了每次调用它时将 t 传递给 inner
之外,我该如何解决这个问题?
如果使用 python 3,那么使用 nonlocal 关键字会让解释器知道使用 outer()
函数的作用域 t:
def outer():
t = 0
def inner():
nonlocal t
t += 1
print(t)
inner()
如果使用python 2,则不能直接赋值给变量,否则会使解释器创建一个新变量t,隐藏外层变量。您可以传入一个可变集合并更新第一项:
def outer():
t = [0]
def inner():
t[0] += 1
print(t[0])
inner()
我有两个嵌套的 python 函数,它们看起来像这样:
def outer():
t = 0
def inner():
t += 1
print(t)
inner()
尝试调用 outer
导致以下错误:
>>> outer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sally.py", line 6, in outer
inner()
File "sally.py", line 4, in inner
t += 1
UnboundLocalError: local variable 't' referenced before assignment
我认为在 t += 1
之前添加行 global t
会有所帮助,但事实并非如此。
为什么会这样?除了每次调用它时将 t 传递给 inner
之外,我该如何解决这个问题?
如果使用 python 3,那么使用 nonlocal 关键字会让解释器知道使用 outer()
函数的作用域 t:
def outer():
t = 0
def inner():
nonlocal t
t += 1
print(t)
inner()
如果使用python 2,则不能直接赋值给变量,否则会使解释器创建一个新变量t,隐藏外层变量。您可以传入一个可变集合并更新第一项:
def outer():
t = [0]
def inner():
t[0] += 1
print(t[0])
inner()