Repository navigation
Expand file tree
/
Copy pathDecoratingClasses.py
More file actions
executable file
·277 lines (219 loc) · 6.07 KB
/
Copy pathDecoratingClasses.py
File metadata and controls
executable file
·277 lines (219 loc) · 6.07 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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 19:28:04 2021
@author: maherme
"""
#%%
# You can modify method of classes:
from fractions import Fraction
Fraction.speak = lambda self, message: 'Fraction says: {0}'.format(message)
f = Fraction(2, 3)
res = f.speak('This is a late parrot')
print(res)
#%%
Fraction.is_integral = lambda self: self.denominator == 1
f1 = Fraction(2, 3)
f2 = Fraction(64, 8)
res = f1.is_integral()
print(res)
res = f2.is_integral()
print(res)
#%%
def dec_speak(cls):
cls.speak = lambda self, message: '{0} says: {1}'.format(self.__class__.__name__, message)
return cls
Fraction = dec_speak(Fraction)
f1 = Fraction(2, 3)
res = f1.speak('hello')
print(res)
#%%
class Person:
pass
Person = dec_speak(Person)
p = Person()
res = p.speak('this works!')
print(res)
#%%
# Let's create some debug decorator:
from datetime import datetime, timezone
def info(self):
results = []
results.append('time: {0}'.format(datetime.now(timezone.utc)))
results.append('Class: {0}'.format(self.__class__.__name__))
results.append('id: {0}'.format(hex(id(self))))
for k, v in vars(self).items(): # vars() is a built-in function that returns all the properties of an object.
results.append('{0}: {1}'.format(k, v))
return results
def debug_info(cls):
cls.debug = info
return cls
@debug_info
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
def say_hi():
return 'Hello there!'
p = Person('John', 1939)
res = p.debug()
print(res)
#%%
# This decorator can be reused in other classes:
@debug_info
class Automobile:
def __init__(self, make, model, year, top_speed):
self.make = make
self.model = model
self.year = year
self.top_speed = top_speed
self._speed = 0
@property # Built-in decorator
def speed(self):
return self._speed
@speed.setter
def speed(self, new_speed):
if new_speed > self.top_speed:
raise ValueError('Speed cannot exceed top_speed.')
else:
self._speed = new_speed
favorite = Automobile('Ford', 'Model T', 1908, 45)
res = favorite.debug()
print(res)
print("-------------------------------")
favorite.speed = 40
res = favorite.debug()
print(res)
#%%
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
p1, p2, p3 = Point(2, 3), Point(2, 3), Point(0, 0)
res = abs(p1)
print(res)
res = p1 is p2
print(res)
res = p1 is p3
print(res)
res = p1 == p2
print(res) # Notice this happens because we have not implemented the equal method.
#%%
# Adding the equal method:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return False
p1, p2, p3 = Point(2, 3), Point(2, 3), Point(0, 0)
res = p1 is p2
print(res)
res = p1 == p2
print(res)
#%%
# We can implement more method:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return False
def __lt__(self, other):
if isinstance(other, Point):
return abs(self) < abs(other)
else:
return NotImplemented
p1, p2, p3 = Point(2, 3), Point(2, 3), Point(0, 0)
res = p1 == p2
print(res)
res = p3 < p1
print(res)
res = p1 > p3
print(res) # This works because python calculates p3 < p1, which is the same
#%%
# We can use decorators and monkey patching:
#
# a <= b if a < b or a == b
# a > b if not(a<b) and a != b
# a >= b if not(a<b)
def complete_ordering(cls):
if '__eq__' in dir(cls) and '__lt__' in dir(cls):
cls.__le__ = lambda self, other: self < other or self == other
cls.__gt__ = lambda self, other: not(self < other) and not(self == other)
cls.__ge__ = lambda self, other: not(self < other)
return cls
@complete_ordering
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return False
def __lt__(self, other):
if isinstance(other, Point):
return abs(self) < abs(other)
else:
return NotImplemented
p1, p2, p3, p4 = Point(2, 3), Point(2, 3), Point(0, 0), Point(100, 200)
res = p1 <= p4
print(res)
res = p4 >= p2
print(res)
res = p1 != p2
print(res)
#%%
# It exists a decorator in the standard library for doing the above:
from functools import total_ordering
@total_ordering
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return False
def __lt__(self, other):
if isinstance(other, Point):
return abs(self) < abs(other)
else:
return NotImplemented
p1, p2, p3, p4 = Point(2, 3), Point(2, 3), Point(0, 0), Point(100, 200)
res = p1 <= p2
print(res)
res = p1 >= p4
print(res)
res = p1 != p2
print(res)