在 Python 3.3.1 中,这有效:
i = 76
def A():
global i
i += 10
print(i) # 76
A()
print(i) # 86
这也有效:
def enclosing_function():
i = 76
def A():
nonlocal i
i += 10
print(i) # 76
A()
print(i) # 86
enclosing_function()
但这不起作用:
i = 76
def A():
nonlocal i # "SyntaxError: no binding for nonlocal 'i' found"
i += 10
print(i)
A()
print(i)
nonlocal
关键字状态的文档(添加了重点):
nonlocal 语句使列出的标识符引用最近的封闭范围中先前绑定的变量。
在第三个示例中,“最近的封闭范围”恰好是全局范围。那么为什么它不起作用呢?
请阅读本文
我确实注意到文档继续说明(强调添加):
[
nonlocal
] 语句允许封装代码重新绑定全局(模块)范围之外的局部范围之外的变量。
但是,严格来说,这并不意味着我在第三个示例中所做的事情不应该起作用。