gpt4 book ai didi

python - 为什么 Python 的 nonlocal 关键字不像全局作用域那样?

转载 作者:太空狗 更新时间:2023-10-29 17:19:15 25 4
gpt4 key购买 nike

在 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 关键字的文档 states (强调):

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope.

在第三个示例中,“最近的封闭范围”恰好是全局范围。那么为什么它不起作用?

请阅读这段内容

我确实注意到文档继续说明(强调):

The [nonlocal] statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

但是,严格来说,这并不意味着我在第三个示例中所做的不应该起作用。

最佳答案

名称的搜索顺序是 LEGB,即 Local、Enclosing、Global、Builtin。所以全局范围不是封闭范围。

编辑

来自docs :

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

关于python - 为什么 Python 的 nonlocal 关键字不像全局作用域那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com