访问封闭作用域中定义的变量 [英] Accessing variables defined in enclosing scope
问题描述
来自关于词法范围的 Google 风格指南:
From the Google Style Guide on lexical scoping:
一个嵌套的 Python 函数可以引用在封闭函数中定义的变量功能,但不能分配给它们.
A nested Python function can refer to variables defined in enclosing functions, but can not assign to them.
这两个似乎一开始都会检查:
Both of these seem to check out at first:
# Reference
def toplevel():
a = 5
def nested():
print(a + 2)
nested()
return a
toplevel()
7
Out[]: 5
# Assignment
def toplevel():
a = 5
def nested():
a = 7 # a is still 5, can't modify enclosing scope variable
nested()
return a
toplevel()
Out[]: 5
那么,为什么嵌套函数中引用和赋值的组合会导致异常?
So why, then, does a combination of both reference and assignment in the nested function lead to an exception?
# Reference and assignment
def toplevel():
a = 5
def nested():
print(a + 2)
a = 7
nested()
return a
toplevel()
# UnboundLocalError: local variable 'a' referenced before assignment
推荐答案
在第一种情况下,您指的是一个 nonlocal
变量,这是可以的,因为没有名为 a<的局部变量/代码>.
In first case, you are referring to a nonlocal
variable which is ok because there is no local variable called a
.
def toplevel():
a = 5
def nested():
print(a + 2) # theres no local variable a so it prints the nonlocal one
nested()
return a
在第二种情况下,您创建一个局部变量 a
这也很好(本地 a
将与非本地变量不同,这就是为什么原始 a
没有改变).
In the second case, you create a local variable a
which is also fine (local a
will be different than the nonlocal one thats why the original a
wasn't changed).
def toplevel():
a = 5
def nested():
a = 7 # create a local variable called a which is different than the nonlocal one
print(a) # prints 7
nested()
print(a) # prints 5
return a
在第三种情况下,您创建了一个局部变量,但在此之前有 print(a+2)
,这就是引发异常的原因.因为 print(a+2)
将引用在该行之后创建的局部变量 a
.
In the third case, you create a local variable but you have print(a+2)
before that and that is why the exception is raised. Because print(a+2)
will refer to the local variable a
which was created after that line.
def toplevel():
a = 5
def nested():
print(a + 2) # tries to print local variable a but its created after this line so exception is raised
a = 7
nested()
return a
toplevel()
为了实现你想要的,你需要在你的内部函数中使用 nonlocal a
:
To achieve what you want, you need to use nonlocal a
inside your inner function:
def toplevel():
a = 5
def nested():
nonlocal a
print(a + 2)
a = 7
nested()
return a
这篇关于访问封闭作用域中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!