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
Viendo ahora - 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
Book Search and Lending Flow in Python OOP
Resumen
Building a functional library system in Python requires more than just storing data. You need to connect users, books, and actions through methods that talk to each other. Here you'll see how to implement book search and the lending flow inside a class-based system, ideal if you're learning object-oriented programming in Python.
How does the book search method work in Python?
The buscar_libro method lives inside the Biblioteca class and follows the same logic we used to find users by ID. Its job is simple: receive a title, walk through the library's book list, and return the one that matches and is available.
The iteration uses a for loop over self.libros, validating two conditions at the same time: that the book's title matches the input and that the book is marked as available. When both are true, the method returns that book instance.
What happens if the book doesn't exist? The method raises a custom exception called
LibroNoDisponibleErrorwith a clear message: "El libro [título] no está disponible o no existe". This avoids silent failures and makes debugging easier.
Notice the detail with lowercase libro versus uppercase Libro. The capital L refers to the class, while the lowercase version is the variable used inside the loop iterator [02:30]. Mixing them up is one of the most common mistakes when you're starting with OOP.
Why use try except when searching for a book?
Because the search can throw an exception, the call inside main.py needs to be wrapped in a try block. The pattern looks like this:
python try: titulo = input("Digite el título del libro: ") libro = biblioteca.buscar_libro(titulo) print(f"El libro que seleccionaste es: {libro}") except LibroNoDisponibleError as e: print(f"Error: {e}")
The as e syntax captures the exception message defined inside the custom error, so the user reads exactly what went wrong without crashing the program.
How do you connect a user to a book loan?
Once you have both pieces, the user found by ID and the book found by title, you can trigger the loan. The Estudiante class inherits from Usuario, and through that inheritance every user type gets access to the solicitar_libro method [04:10].
This method receives the title and returns a result that confirms whether the loan is authorized. Storing that result in a variable lets you print clear feedback in the terminal:
python resultado = usuario.solicitar_libro(titulo) print(f"\n{resultado}")
The \n is a line break that keeps the output readable instead of pasting it right under the previous text. Small detail, big difference in user experience.
What does inheritance mean here? When
Estudianteinherits fromUsuario, it automatically gets all the methods defined inUsuario, includingsolicitar_libro. You don't need to rewrite logic for each user type.
How does the prestar method update book status?
The Libro class implements a protocol that defines a prestar method. This method does three things in sequence:
- Verifies that the book is currently available.
- Sets the
disponibleattribute toFalseautomatically. - Increments the counter of times the book has been lent.
In main.py you call it like this:
python resultado_prestar = libro.prestar() print(resultado_prestar)
Since prestar can also raise a LibroNoDisponibleError, you wrap it in another try except block. This double protection means that whether the failure happens during search or during the actual lending, the program responds gracefully.
What data structure makes testing the system easier?
Before implementing the search, the previous challenge asked you to create a data module containing 10 books and 10 students stored in lists [01:00]. This module gets imported into main.py:
python from data import libros, estudiantes
Having prepopulated lists means you can test the full flow without typing data every run. You grab a cédula from the students list, an existing title like "Orgullo y prejuicio" or "La metamorfosis", and watch the system respond.
When everything connects properly, the terminal shows messages like "Préstamo del libro La metamorfosis está autorizado" followed by "El libro ha sido prestado exitosamente" and the total loan count, which starts at 1 [07:20].
Now your system finds users, finds books, and executes the loan with proper validations at each step. The next move on your side is to break it on purpose: try invalid IDs, books that aren't in the list, or books already lent. What errors show up? Which ones still need to be caught? Drop your findings in the comments.