简体   繁体   English

Python全局命名空间和评估顺序

[英]Python global namespaces and evaluation order

Try this out: 试试看:

A = 1
B = 2
C = A + B

def main():
    global C
    print A

The output of main() is 1 . main()的输出为1

Why is this? 为什么是这样? Why should main get to know about the other global variables used to evaluate C ? 为什么main要了解用于评估C的其他全局变量?

Global variables are always available to all local scopes in Python, including functions. 全局变量始终可用于Python中的所有局部作用域,包括函数。 In this case, within main() A , B , and C are all in scope. 在这种情况下, main() ABC都在范围内。

The global keyword doesn't do what it seems you think it does; global关键字并没有像您认为的那样执行; rather, it permits a local scope to manipulate a global function (it makes global variables "writable", so to speak). 相反,它允许局部作用域操作全局函数(可以说,它使全局变量“可写”)。 Consider these examples: 考虑以下示例:

c = 4
print c
def foo():
    c = 3
    print c
foo()
print c

Here, the output will be 在这里,输出将是

4
3
4

Now, consider this: 现在,考虑一下:

c = 4
print c
def foo():
    global c
    c = 3
    print c
foo()
print c

In this case, the output will be 在这种情况下,输出将是

4
3
3

In the first case, c = 3 merely shadows c until its scope is up (ie when the function definition ends). 在第一种情况下, c = 3仅遮盖c直到其作用域扩展(即,函数定义结束时)。 In the second case, we're actually referring to a reference to a global c after we write global c , so changing the value of c will lead to a permanent change. 在第二种情况下,我们实际上是在编写global c之后引用对全局c的引用,因此更改c的值将导致永久更改。

Functions can read variables in enclosing scopes. 函数可以读取封闭范围内的变量。 The global declaration is used to writing variables (to indiciate that they should be written to the global dictionary rather than the local dictionary). 全局声明用于编写变量(以指示应将其写入全局字典而不是局部字典)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM