Python的程式結構[3] -> 變數/Variable -> 變數類型

來源:互聯網
上載者:User

標籤:局部變數   www.   匯入   ini   users   com   法則   大寫   3.4   

變數類型 / Variable Type

在 Python 中,變數主要有以下幾種,即全域變數,局部變數和內建變數,

 

全域變數 / Global Variable

通常定義於模組內部,大寫變數名形式存在,可被其他模組匯入,但還有一種特殊的私人變數,以單/雙底線開頭,同樣定義於模組內,但無法通過 from modelname import * 的方式進行匯入。

 

局部變數 / Local Variable

局部變數通常定義於函數內部,變數名以小寫形式存在,僅在函數的局部範圍起作用。

 

內建變數 / Built-in Variable

內建變數是一些內建存在的變數,可以通過 vars() 進行查看,常用的有 __name__ 等。

 

變數樣本 / Variable Example


下面以一段代碼來示範這幾種變數之間的區別,

 1 print(vars()) # Show built_in variables 2  3 GLOBAL_VARIABLE = "This is global variable" 4 _PRIVATE_VARIABLE = "This is private variable" 5  6 def call_local(): 7     local_variable = "This is local variable" 8     print(local_variable) 9 10 def call_global():11     global GLOBAL_VARIABLE12     print(GLOBAL_VARIABLE)13 14 def call_private():15     print(_PRIVATE_VARIABLE)16 17 if __name__ == ‘__main__‘:18     call_local()19     call_global()20     call_private()

上面的代碼首先利用 vars() 函數顯示了模組中原始存在的內建變數,主要有 __doc__,__name__ 等。隨後定義了全域變數 GLOBAL_VARIABLE 和私人的全域變數 _PRIVATE_VARIABLE,call_local 函數中對局部變數進行了調用,在 call_global 函數中,首先通過關鍵詞聲明了全域變數,隨後對其進行調用,而在 call_private 函數中卻沒有對私人的全域變數進行 global 聲明,但也成功調用了,這便涉及到了 Python 的 LEGB 法則。

{‘__doc__‘: None, ‘__name__‘: ‘__main__‘, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘C:\\Users\\EKELIKE\\Documents\\Python Note\\3_Program_Structure\\3.4_Variable\\variable_type.py‘, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None}This is local variableThis is global variableThis is private variable

最後,我們在另一個模組中嘗試匯入當前模組的私人全域變數 _PRIVATE_VARIABLE,

 1 from variable_type import * 2  3 print(GLOBAL_VARIABLE) 4  5 try: 6     print(_PRIVATE_VARIABLE) 7 except NameError: 8     print("Name Error, re-import.") 9     from variable_type import _PRIVATE_VARIABLE10     print(_PRIVATE_VARIABLE)

從輸出的結果可以看到,使用 from module import * 的方式是無法將私人的全域變數匯入的,但若指明具體的變數名則可以。

This is global variableName Error, re-import.This is private variable

Note: 此處的全域私人變數使用單底線和雙底線效果相同。

 

 相關閱讀

1. LEGB 法則

Python的程式結構[3] -> 變數/Variable -> 變數類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.