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)文章
Python學(xué)習(xí)小技巧之列表項(xiàng)的排序
這篇文章主要給大家介紹了Python學(xué)習(xí)小技巧之列表項(xiàng)排序的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友們可以參借鑒,下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。2017-05-05Windows系統(tǒng)Python直接調(diào)用C++ DLL的方法
這篇文章主要介紹了Windows系統(tǒng)Python直接調(diào)用C++ DLL文件的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-08-08Python中利用aiohttp制作異步爬蟲及簡單應(yīng)用
asyncio可以實(shí)現(xiàn)單線程并發(fā)IO操作,是Python中常用的異步處理模塊。這篇文章主要介紹了Python中利用aiohttp制作異步爬蟲的相關(guān)知識,需要的朋友可以參考下2018-11-11Python+OpenCV實(shí)現(xiàn)黑白老照片上色功能
我們都知道,有很多經(jīng)典的老照片,受限于那個(gè)時(shí)代的技術(shù),只能以黑白的形式傳世。盡管黑白照片別有一番風(fēng)味,但是彩色照片有時(shí)候能給人更強(qiáng)的代入感。本文就來用Python和OpenCV實(shí)現(xiàn)老照片上色功能,需要的可以參考一下2023-02-02徹底卸載Anaconda詳細(xì)教程(超詳細(xì)!)
這篇文章主要給大家介紹了關(guān)于徹底卸載Anaconda的相關(guān)資料,Anaconda(官方網(wǎng)站)就是可以便捷獲取包且對包能夠進(jìn)行管理,同時(shí)對環(huán)境可以統(tǒng)一管理的發(fā)行版本,需要的朋友可以參考下2023-11-11python實(shí)現(xiàn)QQ郵箱群發(fā)郵件實(shí)例
大家好,本篇文章主要講的是python實(shí)現(xiàn)QQ郵箱群發(fā)郵件實(shí)例,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01