-
Notifications
You must be signed in to change notification settings - Fork 512
/
Copy pathchallenge.py
67 lines (54 loc) · 2.09 KB
/
challenge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Python Object Oriented Programming by Joe Marini course example
# Programming challenge: use inheritance and abstract classes
# Challenge: create a class structure to represent stocks and bonds
# Requirements:
# -- Both stocks and bonds have a price
# -- Stocks have a company name and ticker
# -- Bonds have a description, duration, and yield
# -- You should not be able to instantiate the base class
# -- Subclasses are required to override get_description()
# -- get_description returns formats for stocks and bonds
# For stocks: "Ticker: Company -- $Price"
# For bonds: "description: duration'yr' : $price : yieldamt%"
class Asset(ABC):
def __init__(self, price):
self.price = price
@abstractmethod
def get_description(self):
pass
class Stock(Asset):
def __init__(self, ticker, price, company_name):
super().__init__(price)
self.ticker = ticker
self.company_name = company_name
def get_description(self):
return f"{self.ticker}: {self.company_name} -- ${self.price}"
class Bond(Asset):
def __init__(self, price, description, duration, yieldamt):
super().__init__(price)
self.description = description
self.duration = duration
self.yieldamt = yieldamt
def get_description(self):
return f"{self.description}: {self.duration}yr : ${self.price} : {self.yieldamt}%"
# ~~~~~~~~~ TEST CODE ~~~~~~~~~
try:
ast = Asset(100.0)
except:
print("Can't instantiate Asset!")
msft = Stock("MSFT", 342.0, "Microsoft Corp")
goog = Stock("GOOG", 135.0, "Google Inc")
meta = Stock("META", 275.0, "Meta Platforms Inc")
amzn = Stock("AMZN", 135.0, "Amazon Inc")
us30yr = Bond(95.31, "30 Year US Treasury", 30, 4.38)
us10yr = Bond(96.70, "10 Year US Treasury", 10, 4.28)
us5yr = Bond(98.65, "5 Year US Treasury", 5, 4.43)
us2yr = Bond(99.57, "2 Year US Treasury", 2, 4.98)
print(msft.get_description())
print(goog.get_description())
print(meta.get_description())
print(amzn.get_description())
print(us30yr.get_description())
print(us10yr.get_description())
print(us5yr.get_description())
print(us2yr.get_description())