python 闭包 闭包与装饰器之间的关系

一、一个闭包的实际应用例子

1 def func(a, b):
2     def inner(x):
3         return a * x + b
4     return inner
5 
6 inn = func(1, 1)
7 print(inn(1))
8 inn2 = func(-1, 1)
9 print(inn2(1))

二、闭包传递的参数为函数。

 1 def func(func_temp):
 2     def inner(x):
 3         func_temp(x)
 4     return inner
 5 
 6 
 7 def test(arg):
 8     print('test func. %s' % arg)
 9 
10 
11 inn = func(test)
12 inn('xxx')

三、闭包与修饰器的关系,以下2个例子是等效的。

 1 def check(func):
 2     def inner():
 3         print('def')
 4         func()
 5     return inner
 6 
 7 def foo():
 8     print('abc')
 9 
10 foo = check(foo)    # 闭包
11 foo()
 1 def check(func):
 2     def inner():
 3         print('def')
 4         func()
 5     return inner
 6 
 7 #foo = check(foo)
 8 @check              # 语法糖,装饰器
 9 def foo():
10     print('abc')
11 
12 foo()

 

posted @ 2017-12-30 13:01  魂~  阅读(1010)  评论(0编辑  收藏  举报