1. 文檔說明
在python3.3.2的官方api協助文檔上看到, 如下一段話:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.Names listed in a global statement must not be used in the same code block textually preceding that global statement.Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
翻譯成中文大概意思是:
global語句是適用於當前整個代碼塊的聲明。它是全域變數的標識符。如果某名字在局部名字空間中沒有定義, 就自動使用相應的全域名字. 沒有global是不可能手動指定一個名字是全域的.在 global 中出現的名字不能在global 之前的代碼中使用.在 global 中出現的名字不能作為形參, 不能作為迴圈的控制對象, 不能在類定義, 函數定義, import語句中出現.
與nonlocal關鍵字的區別:
global語句用以知名某個特定的變數為全域範圍,並重新綁定它。nonlocal語句用以指明某個特定的變數為封閉範圍,並重新綁定它。
2. 執行個體說明
def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test()print("In global scope:", spam)
備忘:該執行個體代碼來源於python3.3.2 官方文檔。
運行結果是:
可以看到,只有在與定義方法相平行的代碼中輸出全域變數的值。
def do_global(): global spam spam = "global spam"
假設去掉global關鍵字,運行就會出如下結果:
意思說 span沒有被定義。
總結:
全域變數的使用是為了使我們在一個類或一個函數中使用由函數返回的變數,並進行複雜的計算過程而使用。而對於一個函數的局部變數,則只在一個函數內部是可使用的,而如果需要跨越不同的函數或者類則需要在基礎函數中返回一個該值,在下一個函數中運行其方法才能擷取該值進行計算,如果程式不複雜在一個類中可以解決。全域變數會為我們節省不少的時間,以及記憶體空間。
其他網友對global的用法介紹:http://blog.csdn.net/nilxin/article/details/1523898