Skip to content

Commit 7343b29

Browse files
committed
Complete task-9 Inheritance
1 parent 49db011 commit 7343b29

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

sprint-5-prep/9-inheritance.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Parent:
2+
def __init__(self, first_name: str, last_name: str):
3+
self.first_name = first_name
4+
self.last_name = last_name
5+
6+
def get_name(self) -> str:
7+
return f"{self.first_name} {self.last_name}"
8+
9+
10+
class Child(Parent):
11+
def __init__(self, first_name: str, last_name: str):
12+
super().__init__(first_name, last_name)
13+
self.previous_last_names = []
14+
15+
def change_last_name(self, last_name) -> None:
16+
self.previous_last_names.append(self.last_name)
17+
self.last_name = last_name
18+
19+
def get_full_name(self) -> str:
20+
suffix = ""
21+
if len(self.previous_last_names) > 0:
22+
suffix = f" (née {self.previous_last_names[0]})"
23+
return f"{self.first_name} {self.last_name}{suffix}"
24+
25+
26+
# --- Predictions ---
27+
28+
person1 = Child("Elizaveta", "Alekseeva")
29+
30+
print(person1.get_name())
31+
# Prediction: "Elizaveta Alekseeva"
32+
# Reason: Child inherits get_name() from Parent, no name change yet
33+
34+
print(person1.get_full_name())
35+
# Prediction: "Elizaveta Alekseeva"
36+
# Reason: no previous last names, so suffix is empty string
37+
38+
person1.change_last_name("Tyurina")
39+
# Saves "Alekseeva" into previous_last_names list, changes last_name to "Tyurina"
40+
41+
print(person1.get_name())
42+
# Prediction: "Elizaveta Tyurina"
43+
# Reason: get_name() uses self.last_name which is now "Tyurina"
44+
45+
print(person1.get_full_name())
46+
# Prediction: "Elizaveta Tyurina (nee Alekseeva)"
47+
# Reason: previous_last_names is not empty, so suffix shows the original last name
48+
49+
person2 = Parent("Elizaveta", "Alekseeva")
50+
51+
print(person2.get_name())
52+
# Prediction: "Elizaveta Alekseeva"
53+
# Reason: Parent has get_name(), works normally
54+
55+
# print(person2.get_full_name())
56+
# Prediction: ERROR - AttributeError
57+
# Reason: Parent class does not have get_full_name() method, only Child does
58+
59+
# person2.change_last_name("Tyurina")
60+
# Prediction: ERROR - AttributeError
61+
# Reason: Parent class does not have change_last_name() method, only Child does
62+
63+
# print(person2.get_name())
64+
# Would print "Elizaveta Alekseeva" but we can't reach this line because of the error above
65+
66+
# print(person2.get_full_name())
67+
# Would also error - Parent still doesn't have get_full_name()

0 commit comments

Comments
 (0)