Python中關鍵字nonlocal和global的用法及區別
阿新 • • 發佈:2018-12-14
一、Python3中global
與nonlocal
用法
nonlocal
首先,要明確 nonlocal
關鍵字是定義在閉包裡面的(不定義在閉包裡會拋異常SyntaxError: nonlocal declaration not allowed at module level
)。請看以下程式碼:
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
結果:
inner: 2 outer: 1 global: 0
現在,在閉包裡面加入nonlocal關鍵字進行宣告:
x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
結果:
inner: 2
outer: 2
global: 0
看到區別了麼?這是一個函式裡面再嵌套了一個函式。當使用 nonlocal
時,就聲明瞭該變數不只在巢狀函式inner()
裡面才有效, 而是在整個大函式裡面都有效。
global
還是一樣,看一個例子:
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
結果:
inner: 2
outer: 1
global: 2
global
是對整個環境下的變數起作用,而不是對函式類的變數起作用。
二、Python3中global
與nonlocal
區別
一句話解釋:nonlocal
,如果在閉包內給該變數賦值,那麼修改的其實是閉包外那個作用域中的變數。global
,用來表示對該變數的賦值操作,將會直接修改模組作用域裡
nonlocal
與global
互為補充)——來自《Effective Python》轉自:
https://www.jb51.net/article/108183.htm
http://www.cnblogs.com/brad1994/p/6533267.html