將函數(shù)作為返回值的函數(shù)盾戴,在調(diào)用時(shí)相關(guān)參數(shù)和變量保存在返回的函數(shù)中,這種稱為閉包兵多。
#計(jì)數(shù)器
def createCounter(x=0):
nn = [x]
def counter():
nn[0] += 1
return nn[0]
return counter
count = createCounter(7)
print(count(), count(), count(), count()) -------> (8, 9, 10, 11)
定義count時(shí)還沒有計(jì)算nn[0]的值尖啡,count指向counter()方法,計(jì)算count()時(shí)才會(huì)執(zhí)行nn[0] += 1.