File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ # 练习函数式编程的装饰器
2+ from functools import wraps
3+ import time
4+
5+
6+ # now()
7+ # 现在想在函数里面增加打印log信息,这时又不想修改函数内部,此时可用装饰器
8+ def decorator (func ):
9+ @wraps (func ) # 加这个装饰器是将原函数的__name__等属性复制到这个wrapper函数,防止某些依赖函数签名的代码发生错误
10+ def wrapper (* args , ** kw ):
11+ print ('%s %s()' % ('decorator' , func .__name__ ))
12+ func ()
13+ return wrapper
14+
15+
16+ @decorator
17+ def now ():
18+ print ('2018-02-22' )
19+
20+
21+ now () # 加了装饰器之后再调用该函数就是装饰器里的wrapper()函数内容了
22+ # 在装饰器上也加个wraps装饰器后就可以复制原函数的属性了,此时就变成了原函数名字
23+ print (now .__name__ ) # 此时他的__name__属性也改变了
24+
25+
26+ # 有参数的装饰器
27+ def log (text ):
28+ def decorator (func ):
29+ @wraps (func ) # 记得加这个装饰器防止错误
30+ def wrapper (* args , ** kw ):
31+ print ('%s %s()' % (text , func .__name__ ,))
32+ func (* args , ** kw )
33+ return wrapper
34+ return decorator
35+
36+
37+ @log ('execute' )
38+ def fun ():
39+ print ('now:2018-02-22' )
40+
41+
42+ fun ()
43+ print (fun .__name__ )
44+
45+
46+ # 作业:设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间
47+ def metric (func ):
48+ @wraps (func )
49+ def wrapper (* args , ** kw ):
50+ print (time .time ())
51+ return func (* args , ** kw )
52+ return wrapper
53+
54+
55+ @metric
56+ def fast (x , y ):
57+ time .sleep (0.0012 )
58+ return x + y
59+
60+ @metric
61+ def slow (x , y , z ):
62+ time .sleep (0.1234 )
63+ return x * y * z
64+
65+
66+ print ('作业' )
67+ print (fast (11 , 22 ))
68+ print (slow (11 , 22 , 33 ))
You can’t perform that action at this time.
0 commit comments