說說 Python 的 global 標識對變數作用域的影響
阿新 • • 發佈:2019-12-31
global 標識用於在函式內部,修改全域性變數的值。
我們可以通過以下規則,來判定一個變數到底是在全域性作用域還是區域性作用域:
- 變數定義在全域性作用域,那就是全域性變數。
- 變數在函式中定義,並且加了 global 標識,就是全域性變數。
- 如果變數在函式中僅做了定義,那麼就是區域性變數。
- 如果變數在函式中僅僅是使用,那麼就是全域性變數。
下面的示例,有助於理解上述規則:
def cook():
global dumplings
dumplings = '10' # 全域性變數
print('cook():' + dumplings)
def cook2():
dumplings = '22' # 區域性變數
print('cook2():' + dumplings)
def cook3():
print('cook3():' + dumplings) # 全域性變數
dumplings = 3 # 全域性變數
cook()
print('global:' + dumplings)
cook3()
cook2()
複製程式碼
執行結果:
cook():10 global:10 cook3():10 cook2():22
注意: 在函式中,如果在變數定義之前先使用它,就會拋錯:
def cook():
print(dumplings)
dumplings = 'local'
dumplings = 'global'
cook()
複製程式碼
執行結果:
UnboundLocalError: local variable 'dumplings' referenced before assignment
因為在函式中,存在對 dumplings 的定義賦值語句,所以被認為是區域性變數。所以在定義之前,先訪問這個區域性變數就會拋錯。