nonlocal
首先,要明確 nonlocal 關鍵字是定義在閉包里面的。請看以下代碼:
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 是對整個環境下的變量起作用,而不是對函數類的變量起作用。