-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17a_class_decorators.py
61 lines (48 loc) · 1.73 KB
/
17a_class_decorators.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
# Demonstrates use of decorators with classes in python.
def time_this(old_fn):
print('decorating')
def decorated(*args, **kwargs):
print('starting timer')
import datetime
before = datetime.datetime.now()
x = old_fn(*args, **kwargs)
after = datetime.datetime.now()
print('Time taken = {}'.format(after - before))
return x
return decorated
# Demonstrates use of a decorator on a class.
def time_all_class_methods(OldCls):
class ClassWrapper:
def __init__(self, *args, **kwargs):
self.instance = OldCls(*args, **kwargs)
# This is called whenever an attribute of ClassWrapper is accessed.
# name is the name of the attribute accessed.
# Another method of interest is __call__ for when a function is called.
def __getattribute__(self, name):
# Tries to see if the attribute called actually exists.
try:
x = super().__getattribute__(name)
except AttributeError:
pass
else:
print(name)
return x
x = self.instance.__getattribute__(name)
# Checks if x is an instance method.
if type(x) == type(self.__init__):
# this is equivalent of just decorating the method with time_this.
return time_this(x)
else:
return x
return ClassWrapper
# Demonstrates use of decorators to set class properties.
@time_all_class_methods
class Student:
def __init__(self, name):
self.name = name
def greeting(self):
import time
print('Hi, my name is', self.name)
time.sleep(1)
x = Student('Alice')
x.greeting()