54 lines
1.2 KiB
Markdown
54 lines
1.2 KiB
Markdown
\[ [Index](index.md) | [Exercise 1.4](ex1_4.md) | [Exercise 1.6](ex1_6.md) \]
|
|
|
|
# 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:
|
|
|
|
```python
|
|
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:
|
|
|
|
```python
|
|
>>> 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](soln1_5.md) | [Index](index.md) | [Exercise 1.4](ex1_4.md) | [Exercise 1.6](ex1_6.md) \]
|
|
|
|
----
|
|
`>>>` Advanced Python Mastery
|
|
`...` A course by [dabeaz](https://www.dabeaz.com)
|
|
`...` Copyright 2007-2023
|
|
|
|
. This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/)
|