python中g(shù)lobal與nonlocal比較
python引用變量的順序: 當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量
一、global
global關(guān)鍵字用來(lái)在函數(shù)或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關(guān)鍵字。
gcount = 0
def global_test():
print (gcount)
def global_counter():
global gcount
gcount +=1
return gcount
def global_counter_test():
print(global_counter())
print(global_counter())
print(global_counter())
二、nonlocal
nonlocal關(guān)鍵字用來(lái)在函數(shù)或其他作用域中使用外層(非全局)變量。
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc())
也可以使用generator來(lái)實(shí)現(xiàn)類(lèi)似的counter。如下:
def counter_generator():
count = 0
while True:
count += 1
yield count
def counter_generator_test():
# below is for python 3.x and works well
citer = counter_generator().__iter__()
i = 0
while(i < 3) :
print(citer.__next__())
i+=1
def counter_generator_test2():
#below code don't work
#because next() function still suspends and cannot exit
#it seems the iterator is generated every time.
j = 0
for iter in counter_generator():
while(j < 3) :
print(iter)
j+=1
- Python中的global和nonlocal關(guān)鍵字的使用場(chǎng)景分析
- Python中的global與nonlocal關(guān)鍵字詳解
- 淺析Python中g(shù)lobal和nonlocal關(guān)鍵字的妙用
- Python?nonlocal關(guān)鍵字?與?global?關(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中nonlocal和global的區(qū)別及閉包使用
相關(guān)文章
django ManyToManyField多對(duì)多關(guān)系的實(shí)例詳解
今天小編就為大家分享一篇django ManyToManyField多對(duì)多關(guān)系的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
基于OpenMV的圖像識(shí)別之?dāng)?shù)字識(shí)別功能
OpenMV是一個(gè)開(kāi)源,低成本,功能強(qiáng)大的機(jī)器視覺(jué)模塊。以STM32F427CPU為核心,集成了OV7725攝像頭芯片,在小巧的硬件模塊上,用C語(yǔ)言高效地實(shí)現(xiàn)了核心機(jī)器視覺(jué)算法,提供Python編程接口,對(duì)OpenMV的圖像識(shí)別之?dāng)?shù)字識(shí)別相關(guān)知識(shí)感興趣的朋友一起看看吧2021-11-11
對(duì)pandas通過(guò)索引提取dataframe的行方法詳解
今天小編就為大家分享一篇對(duì)pandas通過(guò)索引提取dataframe的行方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
Python如何管理多個(gè)PostgreSQL數(shù)據(jù)庫(kù)的連接
這篇文章主要為大家詳細(xì)介紹了Python如何通過(guò)讀取配置文件中的PostgreSQL服務(wù)信息,連接到相應(yīng)的PostgreSQL數(shù)據(jù)庫(kù),感興趣的小伙伴可以了解下2024-11-11
Python 對(duì)象序列化與反序列化之pickle json詳細(xì)解析
我們知道在Python中,一切皆為對(duì)象,實(shí)例是對(duì)象,類(lèi)是對(duì)象,元類(lèi)也是對(duì)象。本文正是要聊聊如何將這些對(duì)象有效地保存起來(lái),以供后續(xù)使用2021-09-09

