• 1. 必须有一个内嵌函数
• 2. 内嵌函数必须引用外部函数中的变量
• 3. 外部函数的返回值必须是内嵌函数

### 1.闭包使用示例

In [10]: def func(name):
...:     def in_func(age):
...:         print 'name:',name,'age:',age
...:     return in_func
...:

In [11]: demo = func('feiyu')

In [12]: demo(19)
name: feiyu age: 19

def counter(start=0):
count = [start]
def incr():
count[0] += 1
return count
return incr

a = counter()
print 'a:',a

In [32]: def counter(start=0):
...:     count = start
...:     def incr():
...:         count += 1
...:         return count
...:     return incr
...:

In [33]: a = counter()

In [35]: a()  #此处会报错

UnboundLocalError: local variable 'count' referenced before assignment

In [36]: def counter(start=0):
...:     count = [start]
...:     def incr():
...:         count[0] += 1
...:         return count
...:     return incr
...:

In [37]: count = counter(5)

In [38]: for i in range(10):
...:     print count(),
...:
[6] [7] [8] [9] [10] [11] [12] [13] [14] [15]

### 2.使用闭包的陷阱

In [1]: def create():
...:     return [lambda x:i*x for i in range(5)]  #推导式生成一个匿名函数的列表
...:

In [2]: create()
Out[2]:
[<function __main__.<lambda>>,
<function __main__.<lambda>>,
<function __main__.<lambda>>,
<function __main__.<lambda>>,
<function __main__.<lambda>>]

In [4]: for mul in create():
...:     print mul(2)
...:
8
8
8
8
8

In [5]: def create():
...:         return [lambda x,i=i:i*x for i in range(5)]
...:
In [7]: for mul in create():
...:     print mul(2)
...:
0
2
4
6
8

### 3，闭包与装饰器

def addb(func):
def wrapper():
return '<b>' + func() + '</b>'
return wrapper

def wrapper():
return '<li>' + func() + '</li>'
return wrapper

def demo():
return 'hello world'

print demo()    # 执行的是 addb(addku(demo))

<b><li>hello world</li></b>

### 4.装饰器中的陷阱

def out_func(func):
def wrapper():
func()
return wrapper

@out_func
def demo():
"""
this is  a demo.
"""
print 'hello world.'

if __name__ == '__main__':
demo()
print "__name__:",demo.__name__
print "__doc__:",demo.__doc__

hello world.
__name__: wrapper
__doc__: None

from functools import wraps

def out_func(func):
@wraps(func)
def wrapper():
func()
return wrapper

626062078，我们一起学Python！