Python?nonlocal關(guān)鍵字?與?global?關(guān)鍵字解析
python引用變量的順序: 當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量
1.nonlocal
nonlocal關(guān)鍵字用來(lái)在函數(shù)或其他作用域中使用外層(非全局)變量。
首先:要明確 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ù)里面都有效。
2.global
global關(guān)鍵字用來(lái)在函數(shù)或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關(guān)鍵字。
還是一樣,看一個(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ù)類的變量起作用。
到此這篇關(guān)于Python nonlocal關(guān)鍵字 與 global 關(guān)鍵字解析的文章就介紹到這了,更多相關(guān)nonlocal 與 global 關(guān)鍵字內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中的global和nonlocal關(guān)鍵字的使用場(chǎng)景分析
- Python中的global與nonlocal關(guān)鍵字詳解
- 淺析Python中g(shù)lobal和nonlocal關(guān)鍵字的妙用
- Python關(guān)鍵字之global與nonlocal
- 簡(jiǎn)單了解python關(guān)鍵字global nonlocal區(qū)別
- python global和nonlocal用法解析
- Python中關(guān)鍵字global和nonlocal的區(qū)別詳解
- Python中關(guān)鍵字nonlocal和global的聲明與解析
- python中g(shù)lobal與nonlocal比較
- Python中nonlocal和global的區(qū)別及閉包使用
相關(guān)文章
scrapy爬蟲(chóng)遇到j(luò)s動(dòng)態(tài)渲染問(wèn)題
本文主要介紹了scrapy爬蟲(chóng)遇到j(luò)s動(dòng)態(tài)渲染問(wèn)題,通過(guò)js渲染出來(lái)的動(dòng)態(tài)網(wǎng)頁(yè)的內(nèi)容與網(wǎng)頁(yè)文件內(nèi)容是不一樣的,本文就來(lái)解決一下這些問(wèn)題,感興趣的可以了解一下2022-05-05
使用scrapy ImagesPipeline爬取圖片資源的示例代碼
這篇文章主要介紹了使用scrapy ImagesPipeline爬取圖片資源的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
python中關(guān)于日期時(shí)間處理的問(wèn)答集錦
python中有關(guān)日期時(shí)間處理的問(wèn)答集錦,有需要的朋友不妨參考下2013-03-03
python實(shí)現(xiàn)生命游戲的示例代碼(Game of Life)
這篇文章主要介紹了python實(shí)現(xiàn)生命游戲的示例代碼(Game of Life),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01

