Skip to content

Commit e524c39

Browse files
committed
Complete exercises on type checking, validation, and inheritance
1 parent 2e3050b commit e524c39

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

prep_exercise/9_inheritance.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# play computer game with the code below and predict what you expect each line will do. Then run the code and check your prediction (If any lines cause errors, you may need to comment them out to check later lines).
2+
3+
class Parent:
4+
def __init__(self, first_name: str, last_name: str):
5+
self.first_name = first_name
6+
self.last_name = last_name
7+
8+
def get_name(self) -> str:
9+
return f"{self.first_name} {self.last_name}"
10+
11+
12+
class Child(Parent):
13+
def __init__(self, first_name: str, last_name: str):
14+
super().__init__(first_name, last_name)
15+
self.previous_last_names = []
16+
17+
def change_last_name(self, last_name) -> None:
18+
self.previous_last_names.append(self.last_name)
19+
self.last_name = last_name
20+
21+
def get_full_name(self) -> str:
22+
suffix = ""
23+
if len(self.previous_last_names) > 0:
24+
suffix = f" (née {self.previous_last_names[0]})"
25+
return f"{self.first_name} {self.last_name}{suffix}"
26+
27+
person1 = Child("Elizaveta", "Alekseeva")
28+
print(person1.get_name()) #works because get_name is inherited from Parent.
29+
print(person1.get_full_name()) # get_full_name() works, exist in child.
30+
person1.change_last_name("Tyurina") #change_last_name("Tyurina") works, exist in child..
31+
print(person1.get_name()) # works because it comes from Parent.get_name.
32+
print(person1.get_full_name())# works because it comes from Parent.get_name.
33+
34+
35+
person2 = Parent("Elizaveta", "Alekseeva")
36+
print(person2.get_name()) # works because it is the Parent class.
37+
print(person1.get_full_name())
38+
# print(person2.get_full_name()) #get_full_name is defined only in child
39+
# person2.change_last_name("Tyurina") #change_last_name is defined only in child not in parent
40+
print(person2.get_name())
41+
# print(person2.get_full_name()) #get_full_name is defined only in child not in parent
42+
43+
44+
# ===============What I learned from playing computer game with above code.
45+
46+
# 1. Objects can only call methods they actually have inside them.
47+
# - Creating a parent object does not automatically give the child its behavior
48+
49+
# =====================================================================
50+
#2. Inheritance is "is-a", not "might-be" i.e
51+
# A child is a parent(here the child can inherit freely from the father.)
52+
# A parent is NOT a child(i.e a parent does not inherit from the child)

0 commit comments

Comments
 (0)