Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ac36e03

Browse files
Añadir ejercicio 043-inheritance_and_polymorphism
1 parent b597f4f commit ac36e03

File tree

4 files changed

+145
-0
lines changed

4 files changed

+145
-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+
print(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+
high_school_student.introduce() # Podemos llamar a este método gracias a la herencia
17+
high_school_student.study(4) # Este método ha sido ligeramente modificado y ahora imprime 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 imprimir 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 imprima 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+
print(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+
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
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 print 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 prints 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: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
print(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+
print(f"{self.name} is studying for {hours} hours.")
14+
15+
### DON'T modify the code above ###
16+
17+
### ↓ Your code here ↓ ###
18+
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+
print(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+
print(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+
print(f"Hi there! I'm {self.name}, a college student majoring in {self.major}.")
26+
27+
def attend_lecture(self):
28+
print(f"{self.name} is attending a lecture for {self.major} students.")
29+
30+
31+
college_student = CollegeStudent("Alice", 20, 90, "Computer Science")
32+
college_student.introduce()
33+
college_student.study(3)
34+
college_student.attend_lecture()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /