gpt4 book ai didi

python - 'global' 在 if 语句下如何表现?

转载 作者:太空狗 更新时间:2023-10-30 01:05:33 24 4
gpt4 key购买 nike

在我的程序中,我只在某些情况下需要一个全局变量。假设它看起来像这样:

a = 0
def aa(p):
if p:
global a
a = 1
print("inside the function " + str(a))


print(a)
aa(False)
print("outside the function " + str(a))

我期待的结果是:

0
inside the function 1
outside the function 0

结果是:

0
inside the function 1
outside the function 1

所以,我在想,“好吧,也许 Python 编译器只要看到‘global’关键字,就会使变量成为全局变量,而不管它位于何处”。这是 Python 使用全局变量的方式吗?我是不是误会了?

最佳答案

是的,您理解正确。

global语句不是在运行时评估的东西。它实际上是 解析器 的一个指令,本质上告诉它把所有列出的标识符(此处为 a)视为指代全局范围。来自 the global statement 上的文档:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.

然后它继续说明如何 global确实是一个指令:

Programmer’s note: global is a directive to the parser.

有条件地使用它没有任何区别:它的存在已经在解析阶段被检测到,因此,为获取名称而生成的字节码已经被设置为查看全局范围(使用 LOAD/STORE GLOBAL )。

这就是为什么,如果你dis.dis包含 global 的函数语句,您将看不到 global 的任何相关字节码.使用一个愚蠢的功能:

from dis import dis
def foo():
"I'm silly"
global a

dis(foo)
2 0 LOAD_CONST 0 (None)
2 RETURN_VALUE

没有为 global a 生成任何内容因为它提供的信息已经被使用了!

关于python - 'global' 在 if 语句下如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839363/

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