在一个Python范围,任何分配到该范围内没有声明的变量创建一个新的局部变量除非变量早在函数声明为指的是全球范围变量与关键字global
。
让我们看看你的伪代码的修改版本,看看会发生什么:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
事实上,你可以用一个名为x_local
变量重写所有的func_B
,它将相同的工作。
该命令仅与您的函数执行改变全局x值的操作的顺序相关。因此在我们的例子中,订单并不重要,因为func_B
调用func_A
。在这个例子中,为了此事做:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
注意global
只需要修改全局对象。您仍然可以从一个函数内访问它们而不声明global
。 因此,我们有:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
注create_locally
和access_only
之间的区别 - 尽管没有要求global
access_only
正在访问全局X,即使create_locally
不使用global
或者,它会创建一个本地副本,因为它的分配一个值。
这里的困惑是为什么你不应该使用全局变量。
还要小心,不要因为你的函数中分配了一个变量而认为python会在赋值之前对待引用。在第一次分配之前,如果你使用x,它不会是全局的,或者是本地的。你会在你的脸上得到臭名昭着的UnboundLocalError异常:) – osirisgothra