2.8 KiB
[Index](index.md) | [Exercise 2.6](ex2_6.md) | [Exercise 3.2](ex3_2.md)
Exercise 3.1
Objectives:
- Define a simple class
Files Modified: stock.py
In link:ex1_5.html[Exercise 1.5], you defined a simple class
Stock for representing a holding of stock. In this exercise,
we're simply going to add a few features to that class as well as
write some utility functions.
(a) Adding a new method
Add a new method sell(nshares) to Stock that sells a certain number
of shares by decrementing the share count. Have it work like this:
>>> s = Stock('GOOG',100,490.10)
>>> s.shares
100
>>> s.sell(25)
>>> s.shares
75
>>>
(b) Reading a portfolio
Add a function read_portfolio() to your stock.py program that
reads a file of portfolio data into a list of Stock objects. Here's how it should work:
>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> for s in portfolio:
print(s)
<__main__.Stock object at 0x3902f0>
<__main__.Stock object at 0x390270>
<__main__.Stock object at 0x390330>
<__main__.Stock object at 0x390370>
<__main__.Stock object at 0x3903b0>
<__main__.Stock object at 0x3903f0>
<__main__.Stock object at 0x390430>
>>>
You already wrote a similar function as part of
link:ex2_3.html[Exercise 2.3]. Design discussion: Should
read_portfolio() be a separate function or part of the class
definition?
(c) Printing a Table
Table the data read in part (b) and use it to make a nicely formatted table. For example:
>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> for s in portfolio:
print('%10s %10d %10.2f' % (s.name, s.shares, s.price))
AA 100 32.20
IBM 50 91.10
CAT 150 83.44
MSFT 200 51.23
GE 95 40.37
MSFT 50 65.10
IBM 100 70.44
>>>
Take this code and put it in a function print_portfolio() that
produces the same output, but additionally adds some table headers.
For example:
>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> print_portfolio(portfolio)
name shares price
---------- ---------- ----------
AA 100 32.20
IBM 50 91.10
CAT 150 83.44
MSFT 200 51.23
GE 95 40.37
MSFT 50 65.10
IBM 100 70.44
>>>
[Solution](soln3_1.md) | [Index](index.md) | [Exercise 2.6](ex2_6.md) | [Exercise 3.2](ex3_2.md)
>>> Advanced Python Mastery
... A course by dabeaz
... Copyright 2007-2023
. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License