Inheritance & encapsulation · Herencia y encapsulación
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
Construir sobre una clase existente
- La herencia permite que una nueva clase reutilice una existente.
- La nueva clase es la subclase (hija); la original es la superclase (padre).
- Escribe
class Bird(Animal):—Birdobtiene todos los métodos deAnimal. (En pseudocódigo de examen:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
Llamar al padre con super()
- Una subclase puede añadir sus propios atributos en
__init__. - Usa
super().__init__(...)para ejecutar primero el__init__del padre. - Esto evita repetir el código de configuración del padre.
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
Sobrescribir un método
- Una subclase puede sobrescribir un método: definir uno con el mismo nombre.
- Se usa la versión de la subclase en lugar de la del padre.
- Esto permite que cada clase se comporte a su manera.
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
Encapsulación
- La encapsulación significa mantener los datos de un objeto seguros dentro de él.
- Python no tiene realmente "privado", pero un guion bajo inicial (
self._balance) indica "no tocar desde fuera". - Otro código debería usar métodos para leer o cambiar los datos, no acceder directamente a ellos.
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
Polimorfismo
- El polimorfismo significa un mismo nombre de método, pero diferente comportamiento por clase.
- Un bucle puede llamar a
.speak()en muchos objetos sin conocer su tipo exacto. - Cada objeto responde a su manera.
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
Errores comunes
- Una subclase hereda de su padre y puede añadir o sobrescribir métodos.
- Mantén los datos privados y accede a ellos a través de métodos (encapsulación).
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
Ahora tú practica
- Usa herencia, sobrescritura, encapsulación y llamada a métodos en diferentes objetos.
- Pulsa Comprobar respuesta para probar tu código.
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · Se da la clase Animal. Escribe una subclase Cat(Animal) que herede de ella y añada un método speak(self) que devuelva "Meow". (Debe conservar el name_is heredado).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
The class Shape is given (its area returns · retornos 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · Se da la clase Shape (su area devuelve 0). Escribe Square(Shape): su __init__(self, side) debe llamar a super().__init__("square"), almacenar side, y sobrescribir area para devolver side * side.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Classes Dog and · y Cat are given, each with a speak(). Write speak_all(animals) that returns · retornos a list of each animal's speak() result, in order. · Se dan las clases Dog y Cat, cada una con un speak(). Escribe speak_all(animals) que devuelva una lista con el resultado de speak() de cada animal, en orden.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a class Account whose __init__(self) sets a private balance · equilibrarse self._balance to · hasta 0. Add deposit(self, amount) to add to it, and balance(self) to · hasta return · retorno it. Other code should use these methods, not touch _balance directly. · Escribe una clase Account cuyo __init__(self) establezca un saldo privado self._balance en 0. Añade deposit(self, amount) para sumarle, y balance(self) para devolverlo. El otro código debe usar estos métodos, sin tocar _balance directamente.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.