Skip to content

Commit dfbfb9b

Browse files
authored
Merge pull request #62 from josemoracard/jose11--add-3-class-exercises
Añadir ejercicio 043-inheritance_and_polymorphism
2 parents bbde7f6 + d5fdaff commit dfbfb9b

File tree

5 files changed

+210
-0
lines changed

5 files changed

+210
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# `043` Inheritance and polymorphism
2+
3+
Ahora que entendemos qué es una clase y algunas de sus características, hablemos sobre dos nuevos conceptos relacionados con las clases: herencia y polimorfismo. Considera el siguiente ejemplo:
4+
5+
```py
6+
class HighSchoolStudent(Student): # Agrega la clase padre dentro de los paréntesis
7+
def __init__(self, name, age, grade, specialization):
8+
super().__init__(name, age, grade)
9+
self.specialization = specialization
10+
11+
def study(self, hours):
12+
return f"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams."
13+
14+
# Creando una instancia de HighSchoolStudent
15+
high_school_student = HighSchoolStudent("John", 16, 85, "Science")
16+
print(high_school_student.introduce()) # Podemos llamar a este método gracias a la herencia
17+
print(high_school_student.study(4)) # Este método ha sido ligeramente modificado y ahora retorna un string diferente
18+
```
19+
20+
Suponiendo que la clase `Student` del ejercicio anterior está definida justo encima de esta clase `HighSchoolStudent`, para heredar sus métodos y atributos, simplemente incluimos el nombre de la clase que queremos heredar (la clase padre) dentro de los paréntesis de la clase hija (`HighSchoolStudent`). Como puedes ver, ahora podemos usar el método `introduce` de la clase `Student` sin tener que codificarlo nuevamente, haciendo nuestro código más eficiente. Lo mismo se aplica a los atributos; no necesitamos redefinirlos.
21+
22+
Además, tenemos la flexibilidad de agregar nuevos métodos exclusivamente para esta clase o incluso sobreescribir un método heredado si es necesario, como se demuestra en el método `study` que está ligeramente modificado con respecto a la clase `Student`; esto se llama **polimorfismo**.
23+
24+
## 📝 Instrucciones:
25+
26+
1. Crea una clase llamada `CollegeStudent` que herede de la clase `Student` ya definida.
27+
28+
2. Agrega un nuevo atributo llamado `major` para representar la carrera que están estudiando.
29+
30+
3. Modifica el método heredado `introduce` para retornar este string:
31+
32+
```py
33+
"Hi there! I'm <name>, a college student majoring in <major>."
34+
```
35+
36+
4. Agrega un nuevo método llamado `attend_lecture` que retorne el siguiente string:
37+
38+
```py
39+
"<name> is attending a lecture for <major> students."
40+
```
41+
42+
5. Crea una instancia de tu nueva clase y llama a cada uno de sus métodos. Ejecuta tu código para asegurarte de que funcione.
43+
44+
45+
## 💡 Pista:
46+
47+
+ Puede que hayas notado el uso de un nuevo método `super()`, que es necesario para heredar de una clase padre. Observa dónde se encuentra ubicado y lee más sobre él aquí: [Entendiendo super() en Python](https://realpython.com/python-super/).
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# `043` Inheritance and polymorphism
2+
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+
5+
```py
6+
class HighSchoolStudent(Student): # Add the parent class inside the parenthesis
7+
def __init__(self, name, age, grade, specialization):
8+
super().__init__(name, age, grade)
9+
self.specialization = specialization
10+
11+
def study(self, hours):
12+
return f"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams."
13+
14+
# Creating an instance of HighSchoolStudent
15+
high_school_student = HighSchoolStudent("John", 16, 85, "Science")
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+
```
19+
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.
21+
22+
Additionally, we have the flexibility to add new methods exclusively for this class or even override an inherited method if needed, as demonstrated in the `study` method, which is slightly modified from the `Student` method; this is called **polymorphism**.
23+
24+
## 📝 Instructions:
25+
26+
1. Create a class called `CollegeStudent` which inherits from the already defined `Student` class.
27+
28+
2. Add a new attribute called `major` to represent the major they are studying.
29+
30+
3. Modify the inherited `introduce` method to return this string:
31+
32+
```py
33+
"Hi there! I'm <name>, a college student majoring in <major>."
34+
```
35+
36+
4. Add a new method called `attend_lecture` that returns the following string:
37+
38+
```py
39+
"<name> is attending a lecture for <major> students."
40+
```
41+
42+
5. Create an instance of your newly created class and call each of its methods. Execute your code to ensure it works.
43+
44+
## 💡 Hint:
45+
46+
+ You may have noticed the use of a new method `super()` which is necessary for inheriting from a parent class. Take a look at where it is positioned and have a read about it: [Understanding Python's super()](https://realpython.com/python-super/).
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
### DON'T modify this code ###
2+
3+
class Student:
4+
def __init__(self, name, age, grade):
5+
self.name = name
6+
self.age = age
7+
self.grade = grade
8+
9+
def introduce(self):
10+
return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}."
11+
12+
def study(self, hours):
13+
return f"{self.name} is studying for {hours} hours."
14+
15+
### DON'T modify the code above ###
16+
17+
### ↓ Your code here ↓ ###
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
### DON'T modify this code ###
2+
3+
class Student:
4+
def __init__(self, name, age, grade):
5+
self.name = name
6+
self.age = age
7+
self.grade = grade
8+
9+
def introduce(self):
10+
return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}."
11+
12+
def study(self, hours):
13+
return f"{self.name} is studying for {hours} hours."
14+
15+
### DON'T modify the code above ###
16+
17+
### ↓ Your code here ↓ ###
18+
19+
class CollegeStudent(Student):
20+
def __init__(self, name, age, grade, major):
21+
super().__init__(name, age, grade)
22+
self.major = major
23+
24+
def introduce(self):
25+
return f"Hi there! I'm {self.name}, a college student majoring in {self.major}."
26+
27+
def attend_lecture(self):
28+
return f"{self.name} is attending a lecture for {self.major} students."
29+
30+
31+
college_student = CollegeStudent("Alice", 20, 90, "Computer Science")
32+
print(college_student.introduce())
33+
print(college_student.study(3))
34+
print(college_student.attend_lecture())
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import pytest
2+
from app import CollegeStudent
3+
4+
@pytest.mark.it("The CollegeStudent class should exist")
5+
def test_college_student_class_exists():
6+
try:
7+
assert CollegeStudent
8+
except AttributeError:
9+
raise AttributeError("The class 'CollegeStudent' should exist in app.py")
10+
11+
@pytest.mark.it("The CollegeStudent class includes the 'name' attribute")
12+
def test_college_student_has_name_attribute():
13+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
14+
assert hasattr(college_student, "name")
15+
16+
@pytest.mark.it("The CollegeStudent class includes the 'age' attribute")
17+
def test_college_student_has_age_attribute():
18+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
19+
assert hasattr(college_student, "age")
20+
21+
@pytest.mark.it("The CollegeStudent class includes the 'grade' attribute")
22+
def test_college_student_has_grade_attribute():
23+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
24+
assert hasattr(college_student, "grade")
25+
26+
@pytest.mark.it("The CollegeStudent class includes the 'major' attribute")
27+
def test_college_student_has_major_attribute():
28+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
29+
assert hasattr(college_student, "major")
30+
31+
@pytest.mark.it("The CollegeStudent class includes the 'introduce' method")
32+
def test_college_student_has_introduce_method():
33+
college_student = CollegeStudent("Alice", 22, 90, "Computer Science")
34+
assert hasattr(college_student, "introduce")
35+
36+
@pytest.mark.it("The CollegeStudent class includes the 'study' method")
37+
def test_college_student_has_study_method():
38+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
39+
assert hasattr(college_student, "study")
40+
41+
@pytest.mark.it("The CollegeStudent class includes the 'attend_lecture' method")
42+
def test_college_student_has_attend_lecture_method():
43+
college_student = CollegeStudent("John", 21, 75, "Computer Science")
44+
assert hasattr(college_student, "attend_lecture")
45+
46+
@pytest.mark.it("The introduce method should return the expected string. Testing with different values")
47+
def test_college_student_introduce_method_returns_expected_string():
48+
student1 = CollegeStudent("Alice", 22, 90, "Computer Science")
49+
student2 = CollegeStudent("Bob", 19, 85, "Mathematics")
50+
assert student1.introduce() == "Hi there! I'm Alice, a college student majoring in Computer Science."
51+
assert student2.introduce() == "Hi there! I'm Bob, a college student majoring in Mathematics."
52+
53+
@pytest.mark.it("The study method should return the expected string. Testing with different values")
54+
def test_college_student_study_method_returns_expected_string():
55+
student1 = CollegeStudent("Eve", 20, 78, "Physics")
56+
student2 = CollegeStudent("Charlie", 23, 88, "Chemistry")
57+
assert student1.study(3) == "Eve is studying for 3 hours."
58+
assert student2.study(2) == "Charlie is studying for 2 hours."
59+
60+
@pytest.mark.it("The attend_lecture method should return the expected string. Testing with different values")
61+
def test_college_student_attend_lecture_method_returns_expected_string():
62+
student1 = CollegeStudent("Eve", 20, 78, "Physics")
63+
student2 = CollegeStudent("Charlie", 23, 88, "Chemistry")
64+
assert student1.attend_lecture() == "Eve is attending a lecture for Physics students."
65+
assert student2.attend_lecture() == "Charlie is attending a lecture for Chemistry students."
66+

0 commit comments

Comments
 (0)