2012-12-14 75 views
13

什麼是全局聲明?它是如何使用的?我已閱讀Python's official definition;然而,它對我來說沒有多大意義。在Python中什麼是全局聲明?

+3

只是一句話,2.4是一個老版本的python,[python 2.X版本的實際參考在這裏](http://docs.python.org/2/reference/simple_stmts.html#global) –

+2

Python 3與'global'一起帶有'nonlocal'這個新語句,請參閱。 –

+0

@TahaJahangir - 這是一個很好的觀點。由於您的評論,我還在我的答案中添加了一個關於'nonlocal'的簡介。謝謝! – mgilson

回答

31

每一個 「可變的」 在python被限制在一定範圍內。 python「文件」的範圍是模塊範圍。考慮以下幾點:

#file test.py 
myvariable = 5 # myvariable has module-level scope 

def func(): 
    x = 3  # x has "local" or function level scope. 

本地範圍的對象,一旦死去的函數退出,無法再恢復(除非你return它們),但在一個函數中,您可以在模塊級範圍內訪問變量(或任何包含範圍內):

myvariable = 5 
def func(): 
    print(myvariable) # prints 5 

def func2(): 
    x = 3 
    def func3(): 
     print(x)  # will print 3 because it picks it up from `func2`'s scope 

    func3() 

但是,你不能對參考使用賦值,並期望它會傳播到外部範圍:

myvariable = 5 
def func(): 
    myvariable = 6  # creates a new "local" variable. 
         # Doesn't affect the global version 
    print(myvariable) # prints 6 

func() 
print(myvariable)  # prints 5 

現在,我們終於到了globalglobal關鍵字是告訴python函數中的特定變量在全局(模塊級)範圍內定義的方式。

myvariable = 5 
def func(): 
    global myvariable 
    myvariable = 6 # changes `myvariable` at the global scope 
    print(myvariable) # prints 6 

func() 
print(myvariable) # prints 6 now because we were able 
        # to modify the reference in the function 

換句話說,可以在模塊範圍從func內如果使用global關鍵字改變myvariable值。


順便說一句,範圍可以任意地嵌套:

def func1(): 
    x = 3 
    def func2(): 
     print("x=",x,"func2") 
     y = 4 
     def func3(): 
      nonlocal x # try it with nonlocal commented out as well. See the difference. 
      print("x=",x,"func3") 
      print("y=",y,"func3") 
      z = 5 
      print("z=",z,"func3") 
      x = 10 

     func3() 

    func2() 
    print("x=",x,"func1") 

func1() 
在這種情況下

現在,沒有一個變量在全球範圍內進行申報,並在python2,沒有(容易/ clean)方式將x的值從func3中的func1範圍內更改。這就是爲什麼nonlocal關鍵字是在python3.x中引入的。 nonlocalglobal的擴展,它允許您修改從其他作用域中取出的變量。

+0

+1進行徹底解釋。但是,您可能想要顯示打印語句的結果。 –

+0

@StevenRumbalski - 完成。好建議。 – mgilson

+0

在閱讀您的答案後,我自己對此進行了測試,並且我的理解在此主題上大大改進。非常感謝你! – Capurnicus

0

基本上它告訴解釋器它的給定的變量應該在全局級被修改或分配,而不是默認的本地級。

0
a = 1 

def f(): 
    a = 2 # doesn't affect global a, this new definition hides it in local scope 

a = 1 

def f(): 
    global a 
    a = 2 # affects global a 
0

可以通過聲明它作爲在修改它

的Python要確保你真正瞭解每個功能的全球使用其他功能的全局變量就是你通過明確要求玩什麼全球關鍵字。

this answer參見

1

mgilson做得很好,但我想補充一些。

list1 = [1] 
list2 = [1] 

def main(): 
    list1.append(3) 
    #list1 = [9] 
    list2 = [222] 

    print list1, list2 


print "before main():", list1, list2 
>>> [1] [1] 
main() 
>>> [1,3] [222] 
print list1, list2  
>>> [1, 3] [1] 

在函數裏,Python的假設,除非你把它聲明爲全球每一個變量,局部變量 ,或者你正在訪問一個全局變量。

list1.append(2) 

是可能的,因爲您正在訪問'list1'並且列表是可變的。

list2 = [222] 

是可能的,因爲你正在初始化一個局部變量。

不過,如果你取消註釋#列表1 = [9],你會得到

UnboundLocalError: local variable 'list1' referenced before assignment 

這意味着你正試圖初始化一個新的局部變量「列表1」,但它已經被之前提到, 和你超出範圍重新分配它。

要輸入範圍,請將'list1'聲明爲全局。

我強烈建議您閱讀this,即使最後還是有拼寫錯誤。