欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python函數(shù)中的函數(shù)(閉包)用法實(shí)例

 更新時(shí)間:2016年03月15日 11:17:07   作者:小談博客  
這篇文章主要介紹了Python函數(shù)中的函數(shù)(閉包)用法,結(jié)合實(shí)例形式分析了Python閉包的定義與使用技巧,需要的朋友可以參考下

本文實(shí)例講述了Python閉包的用法。分享給大家供大家參考,具體如下:

Python函數(shù)中也可以定義函數(shù),也就是閉包。跟js中的閉包概念其實(shí)差不多,舉個(gè)Python中閉包的例子。

def make_adder(addend):
 def adder(augend):
  return augend + addend
 return adder
p = make_adder(23)
q = make_adder(44)
print(p(100))
print(q(100))

運(yùn)行結(jié)果是:123和144.

為什么?Python中一切皆對象,執(zhí)行p(100),其中p是make_adder(23)這個(gè)對象,也就是addend這個(gè)參數(shù)是23,你又傳入了一個(gè)100,也就是augend參數(shù)是100,兩者相加123并返回。

有沒有發(fā)現(xiàn)make_adder這個(gè)函數(shù),里面定義了一個(gè)閉包函數(shù),但是make_adder返回的return卻是里面的這個(gè)閉包函數(shù)名,這就是閉包函數(shù)的特征。

再看一個(gè)Python閉包的例子:

def hellocounter (name):
 count=[0]
 def counter():
  count[0]+=1
  print('Hello,',name,',',count[0],' access!')
 return counter
hello = hellocounter('ma6174')
hello()
hello()
hello()

運(yùn)行結(jié)果:

tantengdeMacBook-Pro:learn-python tanteng$ python3 closure.py 
Hello, ma6174 , 1 access!
Hello, ma6174 , 2 access!
Hello, ma6174 , 3 access!

使用閉包實(shí)現(xiàn)了計(jì)數(shù)器的功能,這也是閉包的一個(gè)特點(diǎn),返回的值保存在了內(nèi)存中,所以可以實(shí)現(xiàn)計(jì)數(shù)功能。

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論