-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNote_decorator.py
87 lines (63 loc) · 1.52 KB
/
Note_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
def log(func):
def wrapper(*args, **kw):
print('call %s(): ' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def stop():
print('stop')
stop()
def logging(text):
def decorator(func):
def wrapper(*args, **kwargs):
print('%s %s():' % (text, func.__name__))
return func(*args, **kwargs)
return wrapper
return decorator
@logging('execute')
def now():
print('1234556')
now()
print(now.__name__)
import functools
def print_log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('call %s()' % func.__name__)
return func(*args, **kwargs)
return wrapper
@print_log
def run_log():
print_log('run')
run_log()
print(run_log.__name__)
def log(something):
# if callable, this is a decorator, shape of @log
if callable(something):
func = something
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('call {}'.format(func.__name__))
func(*args, **kwargs)
return wrapper
elif isinstance(something, str):
# else, this is a decorator function, shape of @log(something)
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('{} {}'.format(something, func.__name__))
func(*args, **kwargs)
return wrapper
return decorator
else:
raise AttributeError("Attribute other than str is not supported")
@log
def f():
pass
@log('execute')
def f2():
pass
f()
f2()
print(f.__name__)
print(f2.__name__)