forked from sudharsan2020/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock.py
52 lines (44 loc) · 1.43 KB
/
stock.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
# stock.py
class Stock:
__slots__ = ('name','_shares','_price')
_types = (str, int, float)
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
@classmethod
def from_row(cls, row):
values = [func(val) for func, val in zip(cls._types, row)]
return cls(*values)
@property
def shares(self):
return self._shares
@shares.setter
def shares(self, value):
if not isinstance(value, self._types[1]):
raise TypeError(f'Expected {self._types[1].__name__}')
if value < 0:
raise ValueError('shares must be >= 0')
self._shares = value
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if not isinstance(value, self._types[2]):
raise TypeError(f'Expected {self._types[2].__name__}')
if value < 0:
raise ValueError('price must be >= 0')
self._price = value
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
# Sample
if __name__ == '__main__':
import reader
from tableformat import create_formatter, print_table
portfolio = reader.read_csv_as_instances('../../Data/portfolio.csv', Stock)
formatter = create_formatter('text')
print_table(portfolio,['name','shares','price'], formatter)