Contenido del curso
Encapsulación y Comportamiento de Objetos
Implementar Protocolos con Métodos Especiales
Relaciones entre Clases y Polimorfismo
- 12

Book Search and Lending Flow in Python OOP
08:57 min - 13

Clases abstractas en Python con ABC y @abstractmethod
04:31 min - 14

Decoradores property en Python para atributos con validación
06:22 min - 15

Decoradores @staticmethod y @classmethod en Python
07:18 min - 16

Serialización de objetos Python a JSON para persistencia de datos
07:47 min
Diseño Avanzado y Patrones de Software
Simple Inheritance With Python Classes
Resumen
Reusing code between similar classes is one of the cleanest wins of object oriented programming, and Python makes it straightforward with simple inheritance. You will learn how to build a Usuario base class and extend it into Estudiante and Profesor using super(), method overriding and shared attributes, so your projects scale without duplicated logic.
This walkthrough is for developers stepping into OOP who want a practical example: a small library system where students have a borrowing limit and teachers do not.
What is class inheritance in Python and why does it matter?
Inheritance lets a child class reuse the attributes and methods of a parent class, avoiding repeated code. In the example, both Estudiante and Profesor share nombre and cedula, so those live in the parent class Usuario [00:10].
The pattern starts with a base class built around a constructor that stores the shared data:
python class Usuario: def init(self, nombre, cedula): self.nombre = nombre self.cedula = cedula self.libros_prestados = []
def solicitar_libro(self, titulo): return f"Solicitud del libro {titulo} realizada"
The __init__ method runs automatically every time you create a new instance, which is why it is the right place to assign initial values.
What does
super()do in Python? It calls a method from the parent class without naming it directly. Inside a child__init__,super().__init__(...)runs the parent constructor so shared attributes get set in one place.
How do you extend a parent class using super() in Python?
To inherit, you pass the parent class name in parentheses when declaring the child. Then super() brings the parent constructor into the child without rewriting it [01:05].
Here is the Estudiante class adding two attributes of its own: a carrera and a borrowing cap stored in limite_libros, defaulted to three.
python class Estudiante(Usuario): def init(self, nombre, cedula, carrera): super().init(nombre, cedula) self.carrera = carrera self.limite_libros = 3
Notice the trick: the __init__ inside super() belongs to Usuario, not to Estudiante. Mixing them up is one of the most common bugs when you start with inheritance.
How is the Profesor class different from Estudiante?
The Profesor class also inherits from Usuario, but its borrowing limit is set to None so there is no cap [02:55].
python class Profesor(Usuario): def init(self, nombre, cedula): super().init(nombre, cedula) self.limite_libros = None
That single difference, None versus 3, is what later drives different behavior when each user requests a book.
How do you override methods to add custom logic per subclass?
Method overriding means redefining a parent method inside the child to change its behavior. The base solicitar_libro only returns a generic message, but Estudiante needs to validate the limit before approving a loan [04:20].
The override uses len(self.libros_prestados) to count current loans and compares it against self.limite_libros:
python class Estudiante(Usuario): def solicitar_libro(self, titulo): if len(self.libros_prestados) < self.limite_libros: self.libros_prestados.append(titulo) return f"Préstamo del libro {titulo} autorizado" return f"No puedes prestar más libros. Límite alcanzado: {self.limite_libros}"
For Profesor, the override is simpler: append the title and return confirmation, no validation needed.
What is method overriding? It is when a subclass defines a method with the same name as one in its parent class to replace or extend its behavior. The child version runs whenever you call that method on an instance of the subclass.
Where should shared attributes live in an inheritance hierarchy?
If two child classes use the same attribute, move it up to the parent. The list libros_prestados was first written inside Estudiante, but Profesor also needed it, so the cleanest fix was relocating it to Usuario [06:10].
This is a core principle of inheritance design:
- Put shared state in the parent class.
- Put behavior that varies in the children.
- Override only when the logic genuinely differs.
How do you test inheritance with real instances?
Instantiating a class means calling it with parentheses and arguments, which returns an object you store in a variable. Variable names should start with a lowercase letter as a Python convention.
python estudiante = Estudiante("Luis", "12345", "Ingeniería") profesor = Profesor("Ana", "67890")
print(estudiante.solicitar_libro("Python básico")) print(estudiante.solicitar_libro("Python intermedio")) print(estudiante.solicitar_libro("Python avanzado")) print(estudiante.solicitar_libro("Python Django"))
Running this in the terminal with python usuarios.py shows the first three loans authorized and the fourth blocked with the message No puedes prestar más libros, límite alcanzado: 3 [07:45]. Repeat the same four calls with profesor and all four go through, confirming the difference in behavior.
A quick challenge to lock in the concept: add a method to Estudiante called devolver_libro(titulo) that removes the book from libros_prestados and keeps the list in sync. Drop your version in the comments so we can compare approaches.