本文实例讲述了Python闭包的用法。分享给大家供大家参考,具体如下:
Python函数中也可以定义函数,也就是闭包。跟js中的闭包概念其实差不多,举个Python中闭包的例子。
def make_adder(addend): def adder(augend): return augend + addend return adderp = make_adder(23)q = make_adder(44)print(p(100))print(q(100))
运行结果是:123和144.
为什么?Python中一切皆对象,执行p(100),其中p是make_adder(23)这个对象,也就是addend这个参数是23,你又传入了一个100,也就是augend参数是100,两者相加123并返回。
有没有发现make_adder这个函数,里面定义了一个闭包函数,但是make_adder返回的return却是里面的这个闭包函数名,这就是闭包函数的特征。
再看一个Python闭包的例子:
def hellocounter (name): count=[0] def counter(): count[0]+=1 print('Hello,',name,',',count[0],' access!') return counterhello = hellocounter('ma6174')hello()hello()hello()
运行结果:
tantengdeMacBook-Pro:learn-python tanteng$ python3 closure.py Hello, ma6174 , 1 access!Hello, ma6174 , 2 access!Hello, ma6174 , 3 access!
使用闭包实现了计数器的功能,这也是闭包的一个特点,返回的值保存在了内存中,所以可以实现计数功能。
希望本文所述对大家Python程序设计有所帮助。
新闻热点
疑难解答
图片精选