python中g(shù)lobal與nonlocal比較
python引用變量的順序: 當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量
一、global
global關(guān)鍵字用來在函數(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)鍵字用來在函數(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來實(shí)現(xiàn)類似的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
相關(guān)文章
1分鐘快速生成用于網(wǎng)頁內(nèi)容提取的xslt
這篇文章主要教大家如何1分鐘快速生成用于網(wǎng)頁內(nèi)容提取的xslt,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02詳解Python如何實(shí)現(xiàn)尾遞歸優(yōu)化
尾遞歸是函數(shù)返回最后一個(gè)操作是遞歸調(diào)用,則該函數(shù)是尾遞歸。本文將介紹Python是如何實(shí)現(xiàn)尾遞歸優(yōu)化的,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-05-05Python3實(shí)現(xiàn)轉(zhuǎn)換Image圖片格式
本篇文章給大家分享了Python3實(shí)現(xiàn)在線轉(zhuǎn)換Image圖片格式的功能以及相關(guān)實(shí)例代碼,有興趣的朋友參考下。2018-06-06Python運(yùn)行報(bào)錯(cuò)UnicodeDecodeError的解決方法
本文給大家分享的是在Python項(xiàng)目中經(jīng)常遇到的關(guān)于編碼問題的一個(gè)小bug的解決方法以及分析方法,有相同遭遇的小伙伴可以來參考下2016-06-06Python讀取Pickle文件信息并計(jì)算與當(dāng)前時(shí)間間隔的方法分析
這篇文章主要介紹了Python讀取Pickle文件信息并計(jì)算與當(dāng)前時(shí)間間隔的方法,涉及Python基于pickle模塊操作文件屬性相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-01-01