Skip to content

Commit 47f2cee

Browse files
author
‘Java
committed
class methods
1 parent ce9cbba commit 47f2cee

4 files changed

Lines changed: 173 additions & 0 deletions

File tree

code_with_closures.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def typed_property(name, expected_type):
2+
private_name = '_' + name
3+
4+
@property
5+
def prop(self):
6+
return getattr(self, private_name)
7+
8+
@prop.setter
9+
def prop(self, value):
10+
if not isinstance(value, expected_type):
11+
raise TypeError(f'Expected {expected_type}')
12+
setattr(self, private_name, value)
13+
14+
return prop
15+
16+
17+
Integer = lambda name: typed_property(name, int)
18+
Float = lambda name: typed_property(name, float)
19+
20+
21+
class Holdings:
22+
shares = Integer('shares')
23+
prices = Float('prices')
24+
25+
def __init__(self, name, shares, prices):
26+
self.name = name
27+
self.shares = shares
28+
self.prices = prices
29+
30+
31+
if __name__ == '__main__':
32+
h = Holdings('IBM', 25, 4.1)
33+
print(f'{h.name} cost : {h.shares * h.prices}')
34+
# h.shares = '10' # TypeError: Expected <class 'int'>

container_obj.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
2+
class Holding:
3+
def __init__(self, name, shares, price, date):
4+
self.name = name
5+
self.shares = shares
6+
self.price = price
7+
self.date = date
8+
9+
def cost(self):
10+
return self.price * self.shares
11+
12+
def sell(self, nshares):
13+
self.shares -= nshares
14+
15+
@classmethod
16+
def print_table(cls, objects, col_names):
17+
print(f'Found {len(objects)} records')
18+
for col_name in col_names:
19+
print('{:>10s}'.format(col_name), end=' ')
20+
print()
21+
22+
for obj in objects:
23+
for col_name in col_names:
24+
print('{:>10s}'.format(str(getattr(obj, col_name))), end=' ')
25+
print()
26+
27+
28+
class Portfolio:
29+
30+
def __init__(self):
31+
self.holdings = []
32+
33+
@classmethod
34+
def load(cls):
35+
self = cls()
36+
self.holdings.append(Holding('AA', 23, 45.6, '2023-07-08'))
37+
self.holdings.append(Holding('IBM', 75, 34.6, '2023-06-08'))
38+
self.holdings.append(Holding('IBM', 15, 300.6, '2023-05-01'))
39+
self.holdings.append(Holding('MSFT', 15, 151.6, '2023-07-08'))
40+
return self
41+
42+
def __iter__(self):
43+
return self.holdings.__iter__()
44+
45+
def __len__(self):
46+
return self.holdings.__len__()
47+
48+
def __getattr__(self, item):
49+
# holdings.append and list related function exposed
50+
return getattr(self.holdings, item)
51+
52+
53+
if __name__ == '__main__':
54+
h = Holding('AA', 23, 45.6, '2023-07-08')
55+
print('Class attribute read h.name ', h.name)
56+
h.name = 'Modified'
57+
print('Class attribute set h.name ', h.name)
58+
# del h.name
59+
# AttributeError: 'Holding' object has no attribute 'name'
60+
# print('Class attribute delete h.name ', h.name)
61+
62+
holdings = Portfolio.load()
63+
64+
print(holdings.append)
65+
66+
Holding.print_table(holdings, ['name', 'price'])
67+

context_manager.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def __enter__(self):
2+
print('Entering')
3+
return 'some data'
4+
class Manager:
5+
6+
def __exit__(self, exc_type, exc_val, exc_tb):
7+
print('Existing')
8+
print(exc_type, exc_val, exc_tb)
9+
10+
11+
if __name__ == '__main__':
12+
m = Manager()
13+
with m:
14+
print('some execution')
15+
16+
with m as context:
17+
print(f'Execution with context {context}')
18+
int('n/a')
19+

model.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
class Typed:
3+
expected_type = object
4+
5+
def __init__(self, name):
6+
self.name = name
7+
8+
def __get__(self, instance, cls):
9+
return instance.__dict__[self.name]
10+
11+
def __set__(self, instance, value):
12+
if not isinstance(value, self.expected_type):
13+
raise TypeError(f'Expected {self.expected_type}')
14+
instance.__dict__[self.name] = value
15+
16+
17+
class Integer(Typed):
18+
expected_type = int
19+
20+
21+
class Float(Typed):
22+
expected_type = float
23+
24+
25+
class Holding:
26+
shares = Integer('shares')
27+
price = Float('price')
28+
29+
def __init__(self, name, shares, price):
30+
self.name = name
31+
self.shares = shares
32+
self.price = price
33+
34+
@property
35+
def cost(self):
36+
return self.price * self.shares
37+
38+
39+
if __name__ == '__main__':
40+
h = Holding('IBM', 25, 34.5)
41+
print(f'Share {h.shares} : cost : {h.cost}')
42+
# h.price = '24' # TypeError: Expected <class 'float'>
43+
# h.shares = 'a lot' # TypeError: Expected <class 'int'>
44+
h.shares = 26
45+
print(f'After change: share {h.shares} : cost : {h.cost}')
46+
47+
# t = Integer('test')
48+
# t = 4 # This would override the existing reference
49+
# this would work only inside class
50+
51+
h.append
52+
53+

0 commit comments

Comments
 (0)