Skip to content

Commit d6b758d

Browse files
committed
task: Complete step 9 prep exercises
1 parent 5087237 commit d6b758d

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

prep-exercises/inheritance.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# ------------------------
2+
# Play computer with this code. Predict what you expect each line will do. Then run the code and check your predictions. (If any lines cause errors, you may need to comment them out to check later lines).
3+
# ------------------------
4+
5+
# A.
6+
7+
class Parent:
8+
def __init__(self, first_name: str, last_name: str):
9+
self.first_name = first_name
10+
self.last_name = last_name
11+
12+
def get_name(self) -> str:
13+
return f"{self.first_name} {self.last_name}"
14+
15+
16+
class Child(Parent):
17+
def __init__(self, first_name: str, last_name: str):
18+
super().__init__(first_name, last_name)
19+
self.previous_last_names: list[str] = []
20+
21+
def change_last_name(self, last_name: str) -> None:
22+
self.previous_last_names.append(self.last_name)
23+
self.last_name = last_name
24+
25+
def get_full_name(self) -> str:
26+
suffix = ""
27+
if len(self.previous_last_names) > 0:
28+
suffix = f" (née {self.previous_last_names[0]})"
29+
return f"{self.first_name} {self.last_name}{suffix}"
30+
31+
32+
person1 = Child("Elizaveta", "Alekseeva")
33+
# Predict: person1 has first_name="Elizaveta", last_name="Alekseeva", previous_last_names=[]
34+
35+
print(person1.get_name())
36+
# Checked: prints "Elizaveta Alekseeva"
37+
38+
print(person1.get_full_name())
39+
# Predict + checked: prints "Elizaveta Alekseeva"
40+
41+
person1.change_last_name("Tyurina")
42+
# Predict: previous_last_names becomes ["Alekseeva"], last_name becomes "Tyurina"
43+
44+
print(person1.get_name())
45+
# Predict + checked: prints "Elizaveta Tyurina"
46+
47+
print(person1.get_full_name())
48+
# Predict + checked: prints "Elizaveta Tyurina (née Alekseeva)"
49+
50+
person2 = Parent("Elizaveta", "Alekseeva")
51+
# Predict: person2 has first_name and last_name only
52+
53+
print(person2.get_name())
54+
# Predict + checked: prints "Elizaveta Alekseeva"
55+
56+
# print(person2.get_full_name())
57+
# Predict + checked: AttributeError, because Parent has no get_full_name method
58+
59+
# person2.change_last_name("Tyurina")
60+
# Predict + checked: AttributeError, because Parent has no change_last_name method
61+
62+
print(person2.get_name())
63+
# Predict + checked: still prints "Elizaveta Alekseeva"
64+
65+
# print(person2.get_full_name())
66+
# Predict + checked: AttributeError again for missing Parent.get_full_name

0 commit comments

Comments
 (0)