python-mastery/Exercises/ex3_1.md
2023-07-17 17:45:29 +02:00

103 lines
2.8 KiB
Markdown

\[ [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 [Exercise 1.5](ex1_5.md), 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:
```python
>>> 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:
```python
>>> 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
[Exercise 2.3](ex2_3.md). 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:
```python
>>> 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:
```python
>>> 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](https://www.dabeaz.com)
`...` Copyright 2007-2023
![](https://i.creativecommons.org/l/by-sa/4.0/88x31.png). This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/)