在if语句下,“global”的行为如何?

2024-04-25 17:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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处理全局变量的方式吗?我误解了吗?你知道吗


Tags: the程序falseif编译器def情况function
1条回答
网友
1楼 · 发布于 2024-04-25 17:29:12

是的,你对事情的理解是正确的。你知道吗

global语句不是在运行时计算的。它实际上是解析器指令,它本质上告诉解析器将所有列出的标识符(a这里)视为引用全局范围。从the ^{} 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生成任何内容,因为它提供的信息已被使用!你知道吗

相关问题 更多 >