gpt4 book ai didi

python - 在 Python 中将自由变量视为全局变量?

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:23 26 4
gpt4 key购买 nike

Execution Model section在 Python 3.7 引用手册中,我阅读了以下声明:

The global statement has the same scope as a name binding operation in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.

所以我在 Python 解释器中输入了以下代码:

x =0
def func1():
global x
def func2():
x = 1
func2()

在调用 func1() 之后,我预计全局范围内 x 的值会更改为 1

我做错了什么?

最佳答案

func2 中的

x = 1 不是自由变量。这只是另一个本地人;您绑定(bind)到名称,而绑定(bind)到的名称在默认情况下是本地名称,除非您以其他方式告诉 Python。

来自same Execution model documentation :

If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal or global. [...] If a variable is used in a code block but not defined there, it is a free variable.

(大胆强调我的)

您用x = 1 绑定(bind)了 block 中的名称,因此它是该 block 中的局部变量,不能是自由变量。所以你找到的部分不适用,因为那只适用于自由变量:

If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.

您不应该在 func2() 中绑定(bind) x,因为只有在作用域中绑定(bind)的名称才是自由变量。

所以这是可行的:

>>> def func1():
... global x
... x = 1
... def func2():
... print(x) # x is a free variable here
... func2()
...
>>> func1()
1
>>> x
1
func2 中的

x 现在是一个自由变量;它没有在 func2 的范围内定义,因此从父范围中获取它。这里的父作用域是 func1,但是 x 在那里被标记为全局,所以当读取 x >print() 函数使用全局值。

对比 xfunc1 中没有被标记为全局:

>>> def func1():
... x = 1
... def func2():
... print(x) # x is free variable here, now referring to x in func1
... func2()
...
>>> x = 42
>>> func1()
1

此处全局名称 x 设置为 42,但这并不影响打印的内容。 func2 中的x 是一个自由变量,但是父作用域func1 只有x 作为本地名称。

当您添加一个新的最外层作用域时,它变得更加有趣,其中 x 仍然是本地:

>>> def outerfunc():
... x = 0 # x is a local
... def func1():
... global x # x is global in this scope and onwards
... def func2():
... print('func2:', x) # x is a free variable
... func2()
... print('outerfunc:', x)
... func1()
...
>>> x = 42
>>> outerfunc()
outerfunc: 0
func2: 42
>>> x = 81
>>> outerfunc()
outerfunc: 0
func2: 81
outerfunc 中的

x 是绑定(bind)的,因此不是自由变量。因此,它在该范围内是本地的。但是,在 func1 中,global x 声明将 x 标记为嵌套范围中的全局变量。在 func2 中,x 是一个自由变量,根据您找到的语句,它被视为全局变量。

关于python - 在 Python 中将自由变量视为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52666536/

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