python閉包函數(shù):
閉包,又稱閉包函數(shù)或者閉合函數(shù),類似于嵌套函數(shù),不同之處在于,閉包中外部函數(shù)返回的不是一個(gè)具體的值,而是一個(gè)函數(shù)。一般情況下,返回的函數(shù)會賦值給一個(gè)變量,這個(gè)變量可以在后面被繼續(xù)執(zhí)行調(diào)用。
例如,計(jì)算一個(gè)數(shù)的n次冪,用閉包可以寫成下面的代碼:
#閉包函數(shù),其中exponent稱為自由變量
defnth_power(exponent):
defexponent_of(base):
returnbase**exponent
returnexponent_of#返回值是exponent_of函數(shù)
square=nth_power(2)#計(jì)算一個(gè)數(shù)的平方
cube=nth_power(3)#計(jì)算一個(gè)數(shù)的立方
print(square(2))#計(jì)算2的平方
print(cube(2))#計(jì)算2的立方
運(yùn)行結(jié)果為:
4
8
在上面程序中,外部函數(shù)nth_power()的返回值是函數(shù)exponent_of(),而不是一個(gè)具體的數(shù)值。
需要注意的是,在執(zhí)行完square=nth_power(2)和cube=nth_power(3)后,外部函數(shù)nth_power()的參數(shù)exponent會和內(nèi)部函數(shù)exponent_of一起賦值給squre和cube,這樣在之后調(diào)用square(2)或者cube(2)時(shí),程序就能順利地輸出結(jié)果,而不會報(bào)錯(cuò)說參數(shù)exponent沒有定義。
看到這里,讀者可能會問,為什么要閉包呢?上面的程序,完全可以寫成下面的形式:
defnth_power_rewrite(base,exponent):
returnbase**exponent
上面程序確實(shí)可以實(shí)現(xiàn)相同的功能,不過使用閉包,可以讓程序變得更簡潔易讀。設(shè)想一下,比如需要計(jì)算很多個(gè)數(shù)的平方,那么讀者覺得寫成下面哪一種形式更好呢?
#不使用閉包
res1=nth_power_rewrite(base1,2)
res2=nth_power_rewrite(base2,2)
res3=nth_power_rewrite(base3,2)
#使用閉包
square=nth_power(2)
res1=square(base1)
res2=square(base2)
res3=square(base3)
顯然第二種方式表達(dá)更為簡潔,在每次調(diào)用函數(shù)時(shí),都可以少輸入一個(gè)參數(shù)。
其次,和縮減嵌套函數(shù)的優(yōu)點(diǎn)類似,函數(shù)開頭需要做一些額外工作,當(dāng)需要多次調(diào)用該函數(shù)時(shí),如果將那些額外工作的代碼放在外部函數(shù),就可以減少多次調(diào)用導(dǎo)致的不必要開銷,提高程序的運(yùn)行效率。
以上內(nèi)容為大家介紹了python閉包函數(shù)怎么用,希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。