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

yipeiwu_com7年前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!

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

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

相关文章

使用Python实现企业微信的自动打卡功能

上下班打卡是程序员最讨厌的东西,更讨厌的是设置了连上指定wifi打卡。 手机上有一些定时机器人之类的app,经过实际测试,全军覆没,没一个可以活着走到启动企业微信的这一步,所以还是靠自...

Python数据类型详解(四)字典:dict

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list   列表用[]   元祖:tuple   元祖用()...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

使用go和python递归删除.ds store文件的方法

python版本:复制代码 代码如下:#!/usr/bin/env pythonimport os, sys;def walk(path):  print "cd directory:"...

python opencv3实现人脸识别(windows)

本文实例为大家分享了python人脸识别程序,大家可进行测试 #coding:utf-8 import cv2 import sys from PIL import Ima...