Define a Simple Class

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Define a simple class

Files Modified: stock.py

In 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.

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
>>>

Note:

Complete the sell(nshares) function in the stock.py file.

âœĻ Check Solution and Practice

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('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. Design discussion: Should read_portfolio() be a separate function or part of the class definition?

Note:

Add the read_portfolio() function in the stock.py file.

âœĻ Check Solution and Practice

Printing a Table

Table the data read in step 2 and use it to make a nicely formatted table. For example:

>>> portfolio = read_portfolio('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('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
>>>

Note:

Complete the print_portfolio() function in the stock.py file.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed the Define a Simple Class lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like