Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 50b24ee

Browse files
committed
Exercise 7.11
1 parent b390d87 commit 50b24ee

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

Work/portfolio.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
# Exercises 6.2, 6.3, 6.14
2+
# Exercise 7.11
3+
4+
from fileparse import parse_csv
5+
from stock import Stock
26

37
class Portfolio:
4-
def __init__(self, holdings):
5-
self._holdings = holdings
8+
def __init__(self):
9+
self._holdings = []
610

711
def __iter__(self):
812
return iter(self._holdings)
@@ -16,6 +20,28 @@ def __getitem__(self, index):
1620
def __contains__(self, name):
1721
return any(name == holding.name for holding in self._holdings)
1822

23+
def append(self, holding):
24+
if not isinstance(holding, Stock):
25+
raise TypeError("Expected a Stock instance")
26+
self._holdings.append(holding)
27+
28+
@classmethod
29+
def from_csv(cls, lines, **opts):
30+
self = cls()
31+
32+
portfolio = parse_csv(
33+
lines,
34+
has_headers=True,
35+
select=["name", "shares", "price"],
36+
types={"shares": int, "price": float},
37+
**opts
38+
)
39+
40+
for holding in portfolio:
41+
self.append(Stock(**holding))
42+
43+
return self
44+
1945
@property
2046
def total_cost(self):
2147
return sum(holding.cost for holding in self._holdings)

Work/report.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@
55
# Exercises 4.3-4.8
66
# Exercise 5.6
77
# Exercise 6.2
8-
# Exercises 7.3, 7.4
8+
# Exercises 7.3, 7.4, 7.11
99

1010
from fileparse import parse_csv
1111
from portfolio import Portfolio
12-
from stock import Stock
1312
from tableformat import create_formatter
1413
import sys
1514

@@ -27,16 +26,7 @@ def read_prices(filename, **opts):
2726

2827
def read_portfolio(filename, **opts):
2928
with open(filename, "rt") as file:
30-
portfolio = parse_csv(
31-
file,
32-
has_headers=True,
33-
select=["name", "shares", "price"],
34-
types={"shares": int, "price": float},
35-
**opts
36-
)
37-
return Portfolio([
38-
Stock(**holding) for holding in portfolio
39-
])
29+
return Portfolio.from_csv(file, **opts)
4030

4131
def make_report(portfolio, prices):
4232
report = []

0 commit comments

Comments
 (0)