python-mastery/Exercises/ex1_5.md
2023-07-16 20:21:00 -05:00

1.2 KiB

[ Index | Exercise 1.4 | Exercise 1.6 ]

Exercise 1.5

Objectives:

  • Review of how to define a simple object

Files Created: stock.py

(a) Defining a simple object

Create a file stock.py and define the following class:

class Stock:
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price
    def cost(self):
        return self.shares * self.price

Once you have done this, run your program and experiment with your new Stock object:

>>> s = Stock('GOOG',100,490.10)
>>> s.name
'GOOG'
>>> s.shares
100
>>> s.price
490.1
>>> s.cost()
49010.0
>>> print('%10s %10d %10.2f' % (s.name, s.shares, s.price))
      GOOG        100     490.10
>>> t = Stock('IBM', 50, 91.5)
>>> t.cost()
4575.0
>>> 

[ Solution | Index | Exercise 1.4 | Exercise 1.6 ]


>>> Advanced Python Mastery
... A course by dabeaz
... Copyright 2007-2023

. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License