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