-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass_templates.py
More file actions
49 lines (37 loc) · 1.33 KB
/
class_templates.py
File metadata and controls
49 lines (37 loc) · 1.33 KB
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
import datetime
import functools
import inspect
import time
class TimedMeta(type):
def __new__(mcl, name, bases, nmspc):
for key in nmspc:
value = nmspc[key]
if inspect.isfunction(value):
nmspc[key] = mcl.__wrapped(value)
return super(TimedMeta, mcl).__new__(mcl, name, bases, nmspc)
def __wrapped(func):
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
before_time = datetime.datetime.now()
func(self, *args, **kwargs)
after_time = datetime.datetime.now()
wrapped.timed_sum += (after_time - before_time).microseconds
wrapped.timed_count += 1
wrapped.timed_average = wrapped.timed_sum / wrapped.timed_count
wrapped.timed_sum = 0
wrapped.timed_count = 0
wrapped.timed_average = None
return wrapped
class HealthBot(object, metaclass=TimedMeta):
def draw_blood(self):
time.sleep(2)
def take_blood_pressure(self):
time.sleep(3)
def main():
health_bot = HealthBot()
health_bot.draw_blood()
health_bot.take_blood_pressure()
print('draw_blood: ' + str(health_bot.draw_blood.timed_average))
print('take_blood_pressure: ' + str(health_bot.take_blood_pressure.timed_average))
if __name__ == '__main__':
main()