-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_with_closures.py
More file actions
34 lines (24 loc) · 841 Bytes
/
code_with_closures.py
File metadata and controls
34 lines (24 loc) · 841 Bytes
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
def typed_property(name, expected_type):
private_name = '_' + name
@property
def prop(self):
return getattr(self, private_name)
@prop.setter
def prop(self, value):
if not isinstance(value, expected_type):
raise TypeError(f'Expected {expected_type}')
setattr(self, private_name, value)
return prop
Integer = lambda name: typed_property(name, int)
Float = lambda name: typed_property(name, float)
class Holdings:
shares = Integer('shares')
prices = Float('prices')
def __init__(self, name, shares, prices):
self.name = name
self.shares = shares
self.prices = prices
if __name__ == '__main__':
h = Holdings('IBM', 25, 4.1)
print(f'{h.name} cost : {h.shares * h.prices}')
# h.shares = '10' # TypeError: Expected <class 'int'>