1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Nov 14 01:01:29 2016 @author: toby """ #知识点:装饰器 #装饰器函数 def outer(fun):
def wrapper():
print '验证' #产品经理要求加的验证功能,一下子搞定
print '哈哈'
fun() #这是原来的func1()函数
print 'hello world!' #例如再增加一个
return wrapper
#装饰器是为了装饰一个函数,要想装饰它需要建立某种关系,用”@“符号再加上装饰器函数名:outer @outer def func1():
print 'this is func1'
#调用函数 func1() ''' 加上装饰器之后的执行过程解析: 1、程序从上往下执行,首先解释outer()函数,并把它放到内存里 2、接着继续向下执行,执行到@outer,也就是遇到@outer就又回到outer()函数 3、回到outer()函数里面执行wrapper(),且把func1()当作参数 4、接着执行wrapper()函数里的 print '验证' 5、接着执行wrapper()函数里的 print '哈哈' 5、接着执行wrapper()函数里的fun(),这是原来的func1()函数,func1()函数作为形惨传进来了,接着回到func1()函数执行里面的代码,也就是print 'this is func1'执行完后继续向下执行 6、接着执行print 'hello world!' 7、接着执行return wrapper 结束执行过程 ''' |
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1873457