Home  >  Article  >  Backend Development  >  Python函数中的函数(闭包)用法实例

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

WBOY
WBOYOriginal
2016-06-10 15:05:511304browse

本文实例讲述了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程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn