外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量一、globalglobal關(guān)鍵字用來在函數(shù)或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關(guān)鍵字。復(fù)制代碼代碼如下:gcount=0defglobal_test():print(gcount)defglobal_counter():globalgcountgcount+=1returngcountdefglobal" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python中g(shù)lobal與nonlocal比較

系統(tǒng) 1937 0

python引用變量的順序: 當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量

一、global

global關(guān)鍵字用來在函數(shù)或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關(guān)鍵字。

復(fù)制代碼 代碼如下:

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ù)或其他作用域中使用外層(非全局)變量。

復(fù)制代碼 代碼如下:

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。如下:

復(fù)制代碼 代碼如下:

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


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 鄂尔多斯市| 镇沅| 谢通门县| 华阴市| 新河县| 柳河县| 准格尔旗| 阿巴嘎旗| 平昌县| 赣榆县| 襄汾县| 景洪市| 长治市| 轮台县| 岢岚县| 百色市| 黄浦区| 衡阳市| 恭城| 绥芬河市| 阿拉善左旗| 龙门县| 楚雄市| 汕尾市| 德庆县| 宁明县| 麻栗坡县| 牙克石市| 高碑店市| 大同市| 台中县| 浦东新区| 仙居县| 玉环县| 柞水县| 阳西县| 都兰县| 东莞市| 且末县| 清流县| 泾源县|