为什么 `global` 语句不影响当前块内的块?
Why doesn't `global` statement affect blocks inside current block?
def foo():
global a
def bar():
nonlocal a
a = 6
bar()
a = 5
foo()
print(a)
尝试 运行 由上面列出的代码组成的模块会导致 SyntaxError: no binding for nonlocal 'a' found
。但我预计它会 运行 并打印 6
,为什么不呢?
注意,如果我们将 global a
语句替换为绑定名称 a
的语句(例如 from something import otherthing as a
或 a = 0
),则没有 SyntaxError
,print(a)
语句按预期输出 5
。
我读过 https://docs.python.org/3/reference/executionmodel.html#naming-and-binding 但不明白 global
和 nonlocal
语句的作用。
a = 5
def foo():
global a
def bar():
global a
a = 6
bar()
foo()
print(a)
这会打印出 6
nonlocal 语句导致相应的名称引用最近的封闭函数作用域中先前绑定的变量。
a
绑定在顶级命名空间中。
The nonlocal
statement causes corresponding names to refer to previously bound variables in the nearest enclosing function scope.
但 a
未绑定在函数范围内,因此
SyntaxError
is raised at compile time
换句话说,global
不影响 a
的绑定位置。
def foo():
global a
def bar():
nonlocal a
a = 6
bar()
a = 5
foo()
print(a)
尝试 运行 由上面列出的代码组成的模块会导致 SyntaxError: no binding for nonlocal 'a' found
。但我预计它会 运行 并打印 6
,为什么不呢?
注意,如果我们将 global a
语句替换为绑定名称 a
的语句(例如 from something import otherthing as a
或 a = 0
),则没有 SyntaxError
,print(a)
语句按预期输出 5
。
我读过 https://docs.python.org/3/reference/executionmodel.html#naming-and-binding 但不明白 global
和 nonlocal
语句的作用。
a = 5
def foo():
global a
def bar():
global a
a = 6
bar()
foo()
print(a)
这会打印出 6
nonlocal 语句导致相应的名称引用最近的封闭函数作用域中先前绑定的变量。
a
绑定在顶级命名空间中。
The
nonlocal
statement causes corresponding names to refer to previously bound variables in the nearest enclosing function scope.
但 a
未绑定在函数范围内,因此
SyntaxError
is raised at compile time
换句话说,global
不影响 a
的绑定位置。