我不明白为什么输出是这样的,而不是 1,3,1。
x = 1
def f():
global x
y = x
x = 2
return x + y
print x
print f()
print x
##output:
##
##1
##3
##2
好吧,我知道函数“内部”,global x 告诉函数查看函数外部的 x (x=1)。然后我们将 x=1 放入 y;因此,y=1。现在,local x 为 2,因此 x+y=2+1=3。
那么为什么最后一个 print x 会产生 2? compailer 为什么以及如何“选择”返回本地/全局 x?这两个命令都在函数 statemante 之外..
谢谢!
请您参考如下方法:
没有 local x; global 语句使函数中的所有变量成为全局变量。
因此,x = 2 改变了全局 x。
Python 编译器需要预先知道函数中的名称是局部名称还是全局名称。默认情况下将名称视为全局名称,除非您绑定(bind)到名称(赋值是名称绑定(bind)的一种形式),此时所有在函数中使用变量成为本地。您可以使用 global 语句覆盖此行为,然后将名称的所有使用修复为全局名称,即使该名称已绑定(bind)也是如此。
参见 Naming and binding section在 Python 引用文档中:
If a name is bound in a block, it is a local variable of that block.
和 global statement documentation :
The
globalstatement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.
您不能在一个范围内将名称同时视为全局名称和本地名称。使用不同的名称,就像您对 y 所做的那样。
