博客
关于我
python之函数的闭包(详细讲解并附流程图)
阅读量:677 次
发布时间:2019-03-16

本文共 1403 字,大约阅读时间需要 4 分钟。

闭包的定义

闭包就是函数内部定义的函数。

闭包的逻辑

理解闭包的逻辑之后,有了一定python基础的都可以很容易写出闭包。下面通过案例来讲一下闭包的逻辑。

def discount(x):    if x<0.5 or x>1:        return None    def count(prince, number):        result = prince * number        pay = result * x        print(f'总价是{result}元,实付{pay}元')    return countdiscount(0.8)(2.88, 100)out:总价是288.0元,实付230.4元

以上代码是销售商品时经常遇到的案例,discount函数是外层函数,用来检测打折数字是否合理。count是内层函数,用来计算总金额和实付金额。

python解释器遇到def discount时会在全局命名空间增加一个discount对象,它的值指向discount函数内的代码块。此时discount函数没有运行。

在遇到discount(0.8)(2.88, 100)时开始运行函数discount(0.8),在遇到def count会在discount的局部命名空间增加一个count对象,它的值指向count函数内的代码块。在遇到return count时会把count对象返回给discount(0.8)(2.88,100)。此时discount(0.8)部分已经运行完毕,接下来运行的是count(2.88,100)。count(2.88,100)内部代码块运行完毕后,整个闭包函数运行完毕。

)

闭包的扩展

我们可以通过如下的方式对闭包进行扩展,更加方便使用:

def discount(x):    if x < 0.5 or x > 1:        print('折扣数字不合理。')        return    def count(prince, number):        result = prince * number        pay = result * x        print(f'总价是{result}元,实付{pay}元')    return countgoldcard = discount(0.7)silvercard = discount(0.9)commomcard = discount(1)goldcard(2.88, 100)silvercard(2.88, 100)commomcard(2.88,100)print(id(goldcard))print(id(silvercard))print(id(commomcard))out:总价是288.0元,实付201.6元总价是288.0元,实付259.2元总价是288.0元,实付288.0元198680270409619870813683361987081368192

将外层函数加参数赋值给另外一个变量,相当于定义了一个新的函数,提高了代码复用率。上述goldcard、silvercard、commomcard这3个函数虽然都指向了discount函数,但是因为它们的参数不同,实际上是3个独立的对象,可以看到它们的id各不相同。

转载地址:http://jirqz.baihongyu.com/

你可能感兴趣的文章
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>