-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
53 lines (35 loc) · 1.18 KB
/
model.py
File metadata and controls
53 lines (35 loc) · 1.18 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
class Typed:
expected_type = object
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError(f'Expected {self.expected_type}')
instance.__dict__[self.name] = value
class Integer(Typed):
expected_type = int
class Float(Typed):
expected_type = float
class Holding:
shares = Integer('shares')
price = Float('price')
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
@property
def cost(self):
return self.price * self.shares
if __name__ == '__main__':
h = Holding('IBM', 25, 34.5)
print(f'Share {h.shares} : cost : {h.cost}')
# h.price = '24' # TypeError: Expected <class 'float'>
# h.shares = 'a lot' # TypeError: Expected <class 'int'>
h.shares = 26
print(f'After change: share {h.shares} : cost : {h.cost}')
# t = Integer('test')
# t = 4 # This would override the existing reference
# this would work only inside class
h.append