Python闭包closure

闭包(closure)是函数式编程中一个非常重要的概念。

从字面上理解,就是内嵌函数将外层函数的变量“包”进来,并且“固定”不变,从而形成一个函数。所以一个高阶函数外层输入不同的自变量时,可以创建不同的闭包函数。

def high_order_func(i):
    def enclosing_func(a):
        return a + i

    return enclosing_func


hfunc1 = high_order_func(20)    # 创建闭包函数
print(hfunc1(10))
print(hfunc1(20))               # 变量i仍然固定在闭包函数内,没有失效
print(hfunc1.__closure__)

hfunc2 = high_order_func(50)
print(hfunc2(10))
print(hfunc2.__closure__[0].cell_contents)

输出:
30
40
(<cell at 0x0000010F9A42B4C8: int object at 0x0000000071CA6300>,)
60
50
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值