Python中global用法詳解

來源:互聯網
上載者:User

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.