Python的程序結構[3] -> 變量/Variable -> 變量類型
阿新 • • 發佈:2017-12-24
err ria oca show sta spec mic 內置 document
變量類型 / 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 10def call_global(): 11 global GLOBAL_VARIABLE 12 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 variable
This is global variable
This 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_VARIABLE 10 print(_PRIVATE_VARIABLE)
從輸出的結果可以看到,使用 from module import * 的方式是無法將私有的全局變量導入的,但若指明具體的變量名則可以。
This is global variable Name Error, re-import. This is private variable
Note: 此處的全局私有變量使用單下劃線和雙下劃線效果相同。
相關閱讀
1. LEGB 法則
Python的程序結構[3] -> 變量/Variable -> 變量類型