File tree Expand file tree Collapse file tree 2 files changed +30
-14
lines changed
Expand file tree Collapse file tree 2 files changed +30
-14
lines changed Original file line number Diff line number Diff line change 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
37class 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 )
Original file line number Diff line number Diff line change 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
1010from fileparse import parse_csv
1111from portfolio import Portfolio
12- from stock import Stock
1312from tableformat import create_formatter
1413import sys
1514
@@ -27,16 +26,7 @@ def read_prices(filename, **opts):
2726
2827def 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
4131def make_report (portfolio , prices ):
4232 report = []
You can’t perform that action at this time.
0 commit comments