-
Notifications
You must be signed in to change notification settings - Fork 1
/
Python Decorators
144 lines (92 loc) · 1.94 KB
/
Python Decorators
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
a_string = "This is a global variable"
def foo():
print(locals())
foo()
print(globals() )
def foo(x):
print(locals())
foo(1)
import time
def time_it(func):
def inner(*args):
start=time.time()
func(*args)
end = time.time()
print('use {} seconds'.format(end-start))
return inner
def add(x, y):
print(x+y)
return x+y
@time_it
def sub(x, y):
print(x-y)
return x - y
if __name__ == '__main__':
sub(5,4)
def apply(func, x, y): # 1
return func(x, y) # 2
print(apply(add,2,1))
print(apply(sub,2,1))
def print_func_name(func):
def wrap():
print('Using function {}'.format(func.__name__))
func()
return wrap
def dog_bark():
print("Bark !!!")
def cat_miaow():
print("Miaow ~~~")
if __name__ =='__main__':
print_func_name(dog_bark)()
print_func_name(cat_miaow)()
print_func_name(add(1,2))
def star(func):
def inner(*args,**kwargs):
print('*'*30)
func(*args,**kwargs)
print('*'*30)
return inner
def percent(func):
def inner(*args,**kwargs):
print('%'*30)
func(*args,**kwargs)
print('%'*30)
return inner
@star
@percent
def printer(msg):
print(msg)
printer('Hello')
def respect(maybe):
def congrats():
return 'Congrats Bro'
def insult():
return 'Go away'
if maybe<5:
return congrats
else:
return insult()
print(respect(8))
def wrapper(func):
def status(*args):
print('Start')
func(*args)
print('Finish')
return status
@wrapper
def add(x,y):
print(x+y)
add(3,5)
# measure run time
import time
def measuretime(func):
def wrapper():
starttime = time.perf_counter()
func()
endtime = time.perf_counter()
print(f'Time needed:{endtime - starttime} seconds')
return wrapper
@measuretime
def wastetime():
sum([i**2 for i in range(100000)])
wastetime()