在一個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