-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_decorator.py
111 lines (88 loc) · 1.96 KB
/
log_decorator.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import functools
def log(func):
# 打印日志
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' %func.__name__)
return func(*args,**kw)
return wrapper
@log
def now():
print('2020/04/27')
# print(now())
# print(now.__name__)
def log(text):
# 带有参数
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print('2020/04/27')
# print(now())
# print(now.__name__)
import time,functools
def metric(fn):
# 返回函数运行时间
@functools.wraps(fn)
def wrapper(*args, **kw):
start = time.time()
fn(*args, **kw)
end = time.time() -start
print('%s executed in %.3f ms' %(fn.__name__,end*1000))
return fn(*args, **kw)
return wrapper
# 测试
"""
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
"""
def log(fn):
def decorate(*args, **kw):
print('begin call %s():' %(fn.__name__,))
fn(*args, **kw)
print('end call %s():' %(fn.__name__,))
return decorate()
@log
def now():
print('2020/04/27')
# print(now)
import functools
def log(argv):
# 既支持带参数,也支持不带参数
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('This is decorator')
if type(argv) == str:
print('show %s' % argv)
return func(*args, **kw)
return wrapper
if type(argv) == str:
return deco
else:
return deco(argv)
@log
def f():
print('do f')
@log('execute')
def f1():
print('do f1')
print(f())
print(f1())