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
Loading JSON Data to Restore App State
Resumen
Reading a JSON file to rebuild your application's state is the missing half of persistence in object oriented Python. You already know how to save; now you need a cargar_datos method that opens the file, parses it with json.load and recreates every instance your library needs to keep running.
How do I read a JSON file in Python with the right encoding?
The loading method lives in persistencia.py next to the saving method, and it only takes self because the data comes from a file, not from an instance.
You open the file in read mode using a context manager, keep the same encoding you used when writing, and then parse the content with json.load, which expects a file object.
python with open(self.archivo, "r", encoding="utf-8") as f: datos = json.load(f) print("Datos cargados:", datos)
When you run python main.py, the terminal prints a dictionary with the library nombre, usuarios and libros you saved earlier. That dictionary is the blueprint you will iterate over to rebuild objects.
What does
json.loadreturn in Python? It returns a Python dictionary (or list) built from the JSON file. Keys become strings, and nested structures map directly to dicts and lists.
How do I rebuild objects from a dictionary in Python?
The trick is to read one element, copy its exact shape, and use that shape as the recipe for instantiating your classes.
Start by recreating the library itself. Import the class at the top of persistencia.py and pass the saved name:
python from biblioteca import Biblioteca biblioteca = Biblioteca(datos["nombre"])
How do I recreate a list of books from JSON?
Print datos["libros"][0] once to inspect the shape, then loop over the list and instantiate LibroFisico with every key the constructor expects, including disponible, because a book may have been marked as unavailable before saving.
python from libros import LibroFisico for dato_libro in datos["libros"]: libro = LibroFisico( titulo=dato_libro["titulo"], autor=dato_libro["autor"], isbn=dato_libro["isbn"], disponible=dato_libro["disponible"], ) biblioteca.libros.append(libro)
Even if the class does not require disponible by default, you must pass it to keep the regenerated state identical to what you saved.
How do I distinguish a student from a professor when loading users?
Users mix two classes inside the same list, and the JSON does not carry an explicit tipo field. The practical workaround is to inspect the keys of each dictionary: a student has the carrera key, a professor does not.
python from usuarios import Estudiante, Profesor for dato_usuario in datos["usuarios"]: if "carrera" in dato_usuario: usuario = Estudiante( nombre=dato_usuario["nombre"], cedula=dato_usuario["cedula"], carrera=dato_usuario["carrera"], ) else: usuario = Profesor( nombre=dato_usuario["nombre"], cedula=dato_usuario["cedula"], ) biblioteca.usuarios.append(usuario)
Adding an explicit tipo field when saving would be a cleaner long term practice, but key inspection works perfectly for this project.
How do I wire cargar_datos into main.py?
The loading method must end with return biblioteca so the caller receives a fully populated object ready to use.
In main.py, replace the manual creation of the library, users and books with a single call to the persistence layer, and move the save call to the end so every change is written to disk:
- Delete the hardcoded professor, library, users and example data.
- Assign
biblioteca = persistencia.cargar_datos()at the start. - Call
persistencia.guardar_datos(biblioteca)after the program logic runs.
When you execute python main.py, the application reads biblioteca.json, rebuilds every instance and shows the available books. If you edit the JSON file directly and add a new book, it appears in the app on the next run.
Why use
"r"instead of"w"inopen()?"r"opens the file in read only mode, which is whatjson.loadneeds."w"would erase the file before reading.
What's next after building this Python OOP project?
The project runs, but it is not bulletproof. The most obvious gap is error handling: what happens if biblioteca.json does not exist when cargar_datos runs? Your code will crash with a FileNotFoundError.
Your challenge is to add error handling wherever the application can fail, especially around file reading and JSON parsing. Try try/except blocks for FileNotFoundError and json.JSONDecodeError, and decide whether to create an empty library or stop execution.
Finish your version before checking the final commit in the repository. Then keep practicing, contribute to open source, and continue the Python path. ¿Qué parte de tu proyecto vas a blindar primero con manejo de errores?