Python函数中的函数(闭包)用法实例,python函数


本文实例讲述了Python闭包的用法。分享给大家供大家参考,具体如下:

Python函数中也可以定义函数,也就是闭包。跟js中的闭包概念其实差不多,举个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))

运行结果是: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 counter
hello = 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!

使用闭包实现了计数器的功能,这也是闭包的一个特点,返回的值保存在了内存中,所以可以实现计数功能。

转自:小谈博客 http://www.tantengvip.com/2015/07/python-closure/

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

  • 简析Python的闭包和装饰器
  • 简单讲解Python中的闭包
  • 浅谈Python中的闭包
  • python中的闭包用法实例详解
  • Python闭包实现计数器的方法
  • Python编程中运用闭包时所需要注意的一些地方
  • 详解Python中的装饰器、闭包和functools的教程
  • Python、Javascript中的闭包比较
  • Python中的闭包详细介绍和实例
  • Python中的闭包总结
  • Python深入学习之闭包
  • Python中的闭包实例详解

评论关闭