You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: exercises/043-inheritance_and_polymorphism/README.md
+6-6Lines changed: 6 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
# `043`inheritance and polymorphism
1
+
# `043`Inheritance and polymorphism
2
2
3
3
Now that we understand what a class is and some of its characteristics, let's talk about two new concepts related to classes: inheritance and polymorphism. Consider the following example:
4
4
@@ -9,12 +9,12 @@ class HighSchoolStudent(Student): # Add the parent class inside the parenthesis
9
9
self.specialization = specialization
10
10
11
11
defstudy(self, hours):
12
-
print(f"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams.")
12
+
returnf"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams."
high_school_student.introduce() # We can call this method thanks to inheritance
17
-
high_school_student.study(4) # This method has been slightly modified and now it prints a different string
16
+
print(high_school_student.introduce()) # We can call this method thanks to inheritance
17
+
print(high_school_student.study(4))# This method has been slightly modified and now it returns a different string
18
18
```
19
19
20
20
Assuming that the `Student` class from the previous exercise is coded just above this `HighSchoolStudent` class, to inherit its methods and attributes, we simply include the name of the class we want to inherit from (the parent class) inside the parentheses of the child class (`HighSchoolStudent`). As you can see, we can now use the `introduce` method from the `Student` class without having to code it again, making our code more efficient. The same applies to attributes; we don't need to redefine them.
@@ -27,13 +27,13 @@ Additionally, we have the flexibility to add new methods exclusively for this cl
27
27
28
28
2. Add a new attribute called `major` to represent the major they are studying.
29
29
30
-
3. Modify the inherited `introduce` method to print this string:
30
+
3. Modify the inherited `introduce` method to return this string:
31
31
32
32
```py
33
33
"Hi there! I'm <name>, a college student majoring in <major>."
34
34
```
35
35
36
-
4. Add a new method called `attend_lecture` that prints the following string:
36
+
4. Add a new method called `attend_lecture` that returns the following string:
37
37
38
38
```py
39
39
"<name> is attending a lecture for <major> students."
0 commit comments