forked from sudharsan2020/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock.py
84 lines (68 loc) · 2.47 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
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
# 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
def __repr__(self):
# Note: The !r format code produces the repr() string
return f'{type(self).__name__}({self.name!r}, {self.shares!r}, {self.price!r})'
def __eq__(self, other):
return isinstance(other, Stock) and ((self.name, self.shares, self.price) ==
(other.name, other.shares, other.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 tableformat
import reader
from tableformat import (
print_table,
create_formatter,
TextTableFormatter,
ColumnFormatMixin,
UpperHeadersMixin
)
portfolio = reader.read_csv_as_instances('../../Data/portfolio.csv', Stock)
class PortfolioFormatter(ColumnFormatMixin, TextTableFormatter):
formats = ['%s','%d','%0.2f']
formatter = PortfolioFormatter()
print_table(portfolio,['name','shares','price'], formatter)
class PortfolioFormatter(UpperHeadersMixin, TextTableFormatter):
pass
formatter = PortfolioFormatter()
print_table(portfolio, ['name','shares','price'], formatter)
# Factory function version
formatter = create_formatter('text', column_formats=['%s','%d','%0.2f'])
print_table(portfolio, ['name','shares','price'], formatter)
formatter = create_formatter('text', upper_headers=True)
print_table(portfolio, ['name','shares','price'], formatter)