Exercise 5.1 - Solution

(a) Objects as a Data Structure

# stock.py

class Stock(object):
    '''
    An instance of a stock holding consisting of name, shares, and price.
    '''
    def __init__(self,name,shares,price):
        self.name   = name
        self.shares = shares
        self.price  = price

(b) Reading Data into a List of Objects

# stock.py
...

import csv
def read_portfolio(filename):
    '''
    Read a portfolio file into a list of stock instances.
    '''
    portfolio = []
    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        holding = Stock(row[0], int(row[1]), float(row[2]))
        portfolio.append(holding)
    f.close()
    return portfolio

(c) Adding some methods

# stock.py

class Stock(object):
    '''
    An instance of a stock holding consisting of name, shares, and price.
    '''
    def __init__(self,name,shares,price):
        self.name   = name
        self.shares = shares
        self.price  = price

    def cost(self):
        '''
        Return the cost as shares*price
        '''
        return self.shares*self.price

    def sell(self,nshares):
        '''
        Sell a number of shares and return the remaining number.
        '''
        self.shares -= nshares
        return self.shares

[ Back ]