9. 闭包

9. 闭包

9.1 定义:

a closure is function with an extended scope that encompasses(包含) non-global variables referenced in the body of function but not defined there. It does not matter whether the function is anonymous or not ,what matter is that it can access non-global variables that are defined outside of its body.

If a variable is used in a code block but not defined there, it is a free variable.

概念有点绕,让我们结合示例看一下。

9.2 示例

def make_averager():
    series=[]
    def averager(new_val):
        series.append(new_val)
        return sum(series)/len(series)
    return averager

In [13]: avg=make_averager()

In [14]: avg(9)
Out[14]: 9.0

In [15]: avg(11)
Out[15]: 10.0

在averager作用域内使用了自由变量s,因此它是一个闭包。
注意,series是make_averager函数的局部变量。可是调用avg(9)时,make_averager函数已经返回了,而它的本地作用域也一去不复返了。此时series实际是保存在averager对象中:

>>> avg.__code__.co_varnames
('new_value', 'total')
>>> avg.__code__.co_freevars
('series',)

9.3 总结

综上,闭包是一种函数,它会保留定义函数时存在的自由变量的绑定,这样调用函数时,虽然定义作用域不可用了,但是仍能使用那些绑定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值