闭包,在wikipedia中的解释为:In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.
我的理解是,闭包是由函数和与其相关的引用环境组合而成的实体。闭包的函数中引用了非本地变量,在引用环境中会绑定这些非本地变量的值。
看几个例子吧。
1. 如下代码的的输出是什么?
代码如下
复制代码
flist = []
for i in xrange(3):
def func(x):
return x * i
flist.append(func)
for f in flist:
print f(2)
其实每次打印都是4,因为这里是一个闭包,i在func函数的引用环境中,一起形成了闭包,而i被逐渐变为了2,func都是引用的i,所以当调用f(2)时,i的值是2, f(2)就返回4.
2. 如下代码的的输出是什么?
代码如下
复制代码
def generate_power_func(n):
def nth_power(x):
return x ** n
return nth_power
if __name__ == '__main__':
raised_to_4 = generate_power_func(4)
del generate_power_func
print raised_to_4(2)
这个的输出是16. 因为n是闭包中的引用环境的一部分,即使generate_power_func的生命周期结束了,但由于闭包,在raise_to_4(2)仍然能够调用到n=4。
如果不想使用到闭包的这种特性,可以将外部变量定义为一个容器,如dict、list等,如下示例:
代码如下
复制代码
def outer():
d = {'y': 0}
def inner():
d['y'] += 1
return d['y']
return inner
def foo():
a = [1, ]
def bar():
a[0] = a[0] + 1
return a[0]
return bar
if __name__ == '__main__':
outer = outer()
print outer()
foo = foo()
print foo()
而在python3中,可以在内部函数中用nonlocal关键字来修饰一个变量,以便标识一个变量是非本地变量。
本文的示例代码在:https://github.com/smilejay/python/blob/master/py2014/closure.py