|
| 1 | +# Python Object Oriented Programming by Joe Marini course example |
| 2 | +# Programming challenge: add methods for comparison and equality |
| 3 | + |
| 4 | +from abc import ABC, abstractmethod |
| 5 | + |
| 6 | + |
| 7 | +class Asset(ABC): |
| 8 | + def __init__(self, price): |
| 9 | + self.price = price |
| 10 | + |
| 11 | + @abstractmethod |
| 12 | + def __str__(self): |
| 13 | + pass |
| 14 | + |
| 15 | + |
| 16 | +class Stock(Asset): |
| 17 | + def __init__(self, ticker, price, company): |
| 18 | + super().__init__(price) |
| 19 | + self.company = company |
| 20 | + self.ticker = ticker |
| 21 | + |
| 22 | + |
| 23 | +class Bond(Asset): |
| 24 | + def __init__(self, price, description, duration, yieldamt): |
| 25 | + super().__init__(price) |
| 26 | + self.description = description |
| 27 | + self.duration = duration |
| 28 | + self.yieldamt = yieldamt |
| 29 | + |
| 30 | + |
| 31 | +# ~~~~~~~~~ TEST CODE ~~~~~~~~~ |
| 32 | +stocks = [ |
| 33 | + Stock("MSFT", 342.0, "Microsoft Corp"), |
| 34 | + Stock("GOOG", 135.0, "Google Inc"), |
| 35 | + Stock("META", 275.0, "Meta Platforms Inc"), |
| 36 | + Stock("AMZN", 120.0, "Amazon Inc") |
| 37 | +] |
| 38 | + |
| 39 | +bonds = [ |
| 40 | + Bond(95.31, "30 Year US Treasury", 30, 4.38), |
| 41 | + Bond(96.70, "10 Year US Treasury", 10, 4.28), |
| 42 | + Bond(98.65, "5 Year US Treasury", 5, 4.43), |
| 43 | + Bond(99.57, "2 Year US Treasury", 2, 4.98) |
| 44 | +] |
| 45 | + |
| 46 | +stocks.sort() |
| 47 | +bonds.sort() |
| 48 | + |
| 49 | +for stock in stocks: |
| 50 | + print(stock) |
| 51 | +print("-----------") |
| 52 | +for bond in bonds: |
| 53 | + print(bond) |
0 commit comments