一、Python中global與nonlocal 聲明
如下代碼
a = 10 def foo(): a = 100
執行foo() 結果 a 還是10
函數中對變量的賦值,變量始終綁定到該函數的局部命名空間,使用global 語句可以改變這種行為。
>>> a 10 >>> def foo(): ... global a ... a = 100 ... >>> a 10 >>> foo() >>> a 100
解析名稱時首先檢查局部作用域,然后由內而外一層層檢查外部嵌套函數定義的作用域,如找不到搜索全局命令空間和內置命名空間。
盡管可以層層向外(上)查找變量,但是! ..python2 只支持最里層作用域(局部變量)和全局命令空間(gloabl),也就是說內部函數不能給定義在外部函數中的局部變量重新賦值,比如下面代碼是不起作用的
def countdown(start): n = start def decrement(): n -= 1
python2 中,解決方法可以是是把修改值放到列表或字典中,python3 中,可以使用nonlocal 聲明完成修改
def countdown(start): n = start def decrement(): nonlocal n n -= 1
二、Python nonlocal 與 global 關鍵字解析
nonlocal
首先,要明確 nonlocal 關鍵字是定義在閉包里面的。請看以下代碼:
x = 0def 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 = 0def 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 = 0def 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 是對整個環境下的變量起作用,而不是對函數類的變量起作用。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。
新聞熱點
疑難解答