本文實(shí)例講述了Python 閉包,函數(shù)分隔作用域,nonlocal聲明非局部變量操作。分享給大家供大家參考,具體如下:
實(shí)例對(duì)象也可以實(shí)現(xiàn)閉包的功能,不過實(shí)例對(duì)象消耗的資源(內(nèi)存)比閉包多。
demo.py(閉包):
# 閉包,分割作用域。 外層函數(shù)內(nèi)部嵌套內(nèi)部函數(shù),外層函數(shù)分割變量作用域,并返回內(nèi)部函數(shù)的引用。# 外層函數(shù)負(fù)責(zé)分割作用域,內(nèi)層函數(shù)才是閉包提供的功能。 外層函數(shù)返回內(nèi)層函數(shù)的引用,供外部使用。def my_line(k, b): # k,b只在my_line函數(shù)以及create_y函數(shù)內(nèi)部有效,在外部無效。 比用全局變量節(jié)省資源。 def create_y(x): print(k*x+b) return create_yline_1 = my_line(1, 2)line_1(0)line_1(1)line_1(2)line_2 = my_line(11, 22)line_2(0)line_2(1)line_2(2)
運(yùn)行結(jié)果:
2
3
4
22
33
44
demo.py(nonlocal,聲明閉包中的變量):
x = 100def func_1(): x = 200 def func_2(): # 如果要使用func_1(閉包)中的變量,需要使用nonlocal聲明。 nonlocal x print("x值為:%d" % x) # 200 x = 300 return func_2t1 = func_1()t1()
運(yùn)行結(jié)果:
x值為:200
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注