Skip to content

Commit 891839a

Browse files
committed
inheritance exercise
1 parent 59163b5 commit 891839a

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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: list[str] = []
14+
15+
def change_last_name(self, last_name: str) -> 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+
person1 = Child("Elizaveta", "Alekseeva")
26+
print(person1.get_name())
27+
print(person1.get_full_name())
28+
person1.change_last_name("Tyurina")
29+
print(person1.get_name())
30+
print(person1.get_full_name())
31+
32+
person2 = Parent("Elizaveta", "Alekseeva")
33+
print(person2.get_name())
34+
if isinstance(person2, Child):
35+
print(person2.get_full_name())
36+
person2.change_last_name("Tyurina")
37+
print(person2.get_name())
38+
print(person2.get_full_name())
39+
else:
40+
print("Parent does not have get_full_name() or change_last_name().")
41+
42+
# Predictions vs actual output (play computer):
43+
# 1) Child inherits get_name() from Parent.
44+
# 2) Child-specific get_full_name() shows the maiden name after changing last name.
45+
# 3) Parent supports get_name() only; Child-only methods are unavailable on Parent.
46+
47+
""" When I played computer, I predicted that Child would inherit get_name() from Parent, so person1.get_name() should work exactly like in Parent, while person1.get_full_name() would only exist on Child and add extra detail after a last-name change. Running the code confirmed this: before changing the name, both methods show “Elizaveta Alekseeva”, and after change_last_name("Tyurina"), get_full_name() includes the maiden-name suffix (née Alekseeva). For person2 (a Parent), only get_name() is available, which shows that inheritance gives Child all parent behavior plus additional child-specific methods, but not the other way around. """

0 commit comments

Comments
 (0)