最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中關(guān)鍵字nonlocal和global的聲明與解析

 更新時(shí)間:2017年03月12日 11:58:14   作者::Brad1994  
這篇文章主要給大家介紹了關(guān)于Python中關(guān)鍵字nonlocal和global的聲明與解析的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。

一、Python中g(shù)lobal與nonlocal 聲明

如下代碼

a = 10 
 
def foo(): 
 a = 100 

執(zhí)行foo() 結(jié)果 a 還是10

函數(shù)中對(duì)變量的賦值,變量始終綁定到該函數(shù)的局部命名空間,使用global 語(yǔ)句可以改變這種行為。

>>> a 
10 
>>> def foo(): 
...  global a 
...  a = 100 
... 
>>> a 
10 
>>> foo() 
>>> a 
100 

解析名稱(chēng)時(shí)首先檢查局部作用域,然后由內(nèi)而外一層層檢查外部嵌套函數(shù)定義的作用域,如找不到搜索全局命令空間和內(nèi)置命名空間。

盡管可以層層向外(上)查找變量,但是! ..python2 只支持最里層作用域(局部變量)和全局命令空間(gloabl),也就是說(shuō)內(nèi)部函數(shù)不能給定義在外部函數(shù)中的局部變量重新賦值,比如下面代碼是不起作用的

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 關(guān)鍵字解析

nonlocal

首先,要明確 nonlocal 關(guān)鍵字是定義在閉包里面的。請(qǐng)看以下代碼:

x = 0
def outer():
 x = 1
 def inner():
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

結(jié)果

# inner: 2
# outer: 1
# global: 0

現(xiàn)在,在閉包里面加入nonlocal關(guān)鍵字進(jìn)行聲明:

x = 0
def outer():
 x = 1
 def inner():
  nonlocal x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

結(jié)果

# inner: 2
# outer: 2
# global: 0

看到區(qū)別了么?這是一個(gè)函數(shù)里面再嵌套了一個(gè)函數(shù)。當(dāng)使用 nonlocal 時(shí),就聲明了該變量不只在嵌套函數(shù)inner()里面
才有效, 而是在整個(gè)大函數(shù)里面都有效。

global

還是一樣,看一個(gè)例子:

x = 0
def outer():
 x = 1
 def inner():
  global x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

結(jié)果

# inner: 2
# outer: 1
# global: 2

global 是對(duì)整個(gè)環(huán)境下的變量起作用,而不是對(duì)函數(shù)類(lèi)的變量起作用。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論

西华县| 阳信县| 湘乡市| 民县| 卢氏县| 明溪县| 江北区| 高雄县| 宝应县| 浦城县| 黔南| 锡林浩特市| 明水县| 平山县| 英吉沙县| 旅游| 巴林左旗| 肃宁县| 新余市| 开远市| 大悟县| 辉县市| 荃湾区| 渭源县| 明溪县| 黎平县| 方正县| 平利县| 永吉县| 内丘县| 佛山市| 读书| 湘阴县| 咸阳市| 双流县| 大城县| 海门市| 隆回县| 紫阳县| 寻甸| 灌云县|