|
| 1 | +# 26 SOLID: PRINCIPIO DE RESPONSABILIDAD ÚNICA (SRP) |
| 2 | +import logging |
| 3 | +# Ejercicio |
| 4 | +# Ejemplo Pato sin SRP |
| 5 | + |
| 6 | + |
| 7 | +class Pato: |
| 8 | + |
| 9 | + def __init__(self, nombre): |
| 10 | + self.nombre = nombre |
| 11 | + |
| 12 | + def vuela(self): |
| 13 | + print(f"{self.nombre} vuela.") |
| 14 | + |
| 15 | + def nada(self): |
| 16 | + print(f"{self.nombre} nada.") |
| 17 | + |
| 18 | + def dice(self) -> str: |
| 19 | + return "Quack" |
| 20 | + |
| 21 | + def saluda(self, pato2): |
| 22 | + print(f"{self.nombre}: {self.dice()}, hola {pato2.nombre}") |
| 23 | + |
| 24 | + |
| 25 | +# Uso |
| 26 | +print("Sin SRP") |
| 27 | +pato1 = Pato(nombre="Daisy") |
| 28 | +pato2 = Pato(nombre="Donald") |
| 29 | +pato1.vuela() |
| 30 | +pato1.nada() |
| 31 | +pato1.saluda(pato2) |
| 32 | +print("\n") |
| 33 | + |
| 34 | +# Ejemplo Pato con SRP |
| 35 | + |
| 36 | + |
| 37 | +class Pato(): |
| 38 | + """Clase que define los patos""" |
| 39 | + |
| 40 | + def __init__(self, nombre): |
| 41 | + self.nombre = nombre |
| 42 | + |
| 43 | + def vuela(self): |
| 44 | + print(f"{self.nombre} vuela.") |
| 45 | + |
| 46 | + def nada(self): |
| 47 | + print(f"{self.nombre} nada.") |
| 48 | + |
| 49 | + def dice(self) -> str: |
| 50 | + return "Quack" |
| 51 | + |
| 52 | + |
| 53 | +class Dialogo(): |
| 54 | + """Clase que define la comunicacion entre patos""" |
| 55 | + |
| 56 | + def __init__(self, formato): |
| 57 | + self.formato = formato |
| 58 | + |
| 59 | + def conversacion(self, pato1: Pato, pato2: Pato): |
| 60 | + frase1 = f"{pato1.nombre}: {pato1.dice()}, ¡Ay, { |
| 61 | + pato2.nombre}! ¡Casi me caigo al intentar atrapar un pez!" |
| 62 | + frase2 = f"{pato2.nombre}: {pato2.dice()}, ¡Otra vez, { |
| 63 | + pato1.nombre}? Ten más cuidado la próxima vez." |
| 64 | + conversacion = [frase1, frase2] |
| 65 | + print(*conversacion, |
| 66 | + f"(Extracto de {self.formato})", |
| 67 | + sep='\n') |
| 68 | + |
| 69 | + |
| 70 | +# Uso |
| 71 | +print("Con SRP") |
| 72 | +pato1 = Pato(nombre="Donald") |
| 73 | +pato2 = Pato(nombre="Daisy") |
| 74 | +pato1.vuela() |
| 75 | +pato2.nada() |
| 76 | +formato1 = Dialogo(formato="historieta") |
| 77 | +formato1.conversacion(pato1, pato2) |
| 78 | + |
| 79 | +# Extra |
| 80 | +# Programa sin SRP |
| 81 | + |
| 82 | + |
| 83 | +class GestorBiblioteca(): |
| 84 | + """ |
| 85 | + Clase que gestiona una biblioteca. |
| 86 | + """ |
| 87 | + |
| 88 | + def __init__(self): |
| 89 | + self.registro = {} |
| 90 | + self.usuarios = {} |
| 91 | + |
| 92 | + def registro_libros(self, id, titulo, autor, cantidad_copias, max_prestamo): |
| 93 | + """ |
| 94 | + Funcion que registra un libro. |
| 95 | + """ |
| 96 | + nuevo_libro = { |
| 97 | + "titulo": titulo, |
| 98 | + "autor": autor, |
| 99 | + "cantidad_copias": cantidad_copias, |
| 100 | + "max_prestamo": max_prestamo |
| 101 | + } |
| 102 | + self.registro[id] = nuevo_libro |
| 103 | + print(f"Libro '{titulo}' agregado con éxito.") |
| 104 | + |
| 105 | + def agregar_usuario(self, id, nombre, dni, email): |
| 106 | + """ |
| 107 | + Funcion que permite agregar nuevos usuarios con información básica. |
| 108 | + """ |
| 109 | + nuevo_usuario = { |
| 110 | + "nombre": nombre, |
| 111 | + "dni": dni, |
| 112 | + "email": email |
| 113 | + } |
| 114 | + self.usuarios[id] = nuevo_usuario |
| 115 | + print(f"Usuario '{nombre}' agregado con éxito.") |
| 116 | + |
| 117 | + def prestamo_libro(self, titulo, nombre): |
| 118 | + """ |
| 119 | + Funcion para que los usuarios puedan tomar prestados libros. |
| 120 | + """ |
| 121 | + usuario_registrado = False |
| 122 | + for usuario in self.usuarios.values(): |
| 123 | + if usuario["nombre"] == nombre: |
| 124 | + usuario_registrado = True |
| 125 | + break |
| 126 | + |
| 127 | + if not usuario_registrado: |
| 128 | + print(f"Usuario '{ |
| 129 | + nombre}' no está registrado. No puede tomar prestado libros para llevar a casa.") |
| 130 | + return |
| 131 | + |
| 132 | + libro_prestado = None |
| 133 | + cantidad_actual = None |
| 134 | + |
| 135 | + for id, nuevo_registro in self.registro.items(): |
| 136 | + if nuevo_registro["titulo"] == titulo: |
| 137 | + libro_prestado = nuevo_registro |
| 138 | + cantidad_actual = nuevo_registro["cantidad_copias"] |
| 139 | + max_prestamo = nuevo_registro["max_prestamo"] |
| 140 | + break |
| 141 | + |
| 142 | + if libro_prestado: |
| 143 | + if cantidad_actual > 0 and cantidad_actual <= max_prestamo: |
| 144 | + cantidad_actual -= 1 |
| 145 | + libro_prestado["cantidad_copias"] = cantidad_actual |
| 146 | + print(f"Libro '{titulo}' prestado con éxito a {nombre}.") |
| 147 | + else: |
| 148 | + print(f"Libro '{ |
| 149 | + titulo}' no tiene copias disponibles o se ha excedido el máximo préstamo.") |
| 150 | + else: |
| 151 | + print(f"Libro '{titulo}' sin existencias.") |
| 152 | + |
| 153 | + def devolucion_libro(self, titulo, nombre): |
| 154 | + """ |
| 155 | + Funcion para que los usuarios puedan devolver libros. |
| 156 | + """ |
| 157 | + usuario_registrado = False |
| 158 | + for usuario in self.usuarios.values(): |
| 159 | + if usuario["nombre"] == nombre: |
| 160 | + usuario_registrado = True |
| 161 | + break |
| 162 | + |
| 163 | + if not usuario_registrado: |
| 164 | + print(f"Usuario '{ |
| 165 | + nombre}' no está registrado. Pida el nombre o id de la persona que tomo prestado el libro.") |
| 166 | + return |
| 167 | + |
| 168 | + libro_devuelto = None |
| 169 | + |
| 170 | + for id, nuevo_registro in self.registro.items(): |
| 171 | + if nuevo_registro["titulo"] == titulo: |
| 172 | + libro_devuelto = nuevo_registro |
| 173 | + cantidad_actual = nuevo_registro["cantidad_copias"] |
| 174 | + max_prestamo = nuevo_registro["max_prestamo"] |
| 175 | + break |
| 176 | + |
| 177 | + if libro_devuelto: |
| 178 | + cantidad_actual_nueva = cantidad_actual + 1 |
| 179 | + if cantidad_actual_nueva <= max_prestamo: |
| 180 | + cantidad_actual += 1 |
| 181 | + libro_devuelto["cantidad_copias"] = cantidad_actual |
| 182 | + print(f"Libro '{titulo}' devuelto con éxito por {nombre}.") |
| 183 | + else: |
| 184 | + print( |
| 185 | + f"Se ha superado el límite máximo de libros para '{titulo}'.") |
| 186 | + else: |
| 187 | + print(f"Libro '{titulo}' no pertenece a la biblioteca.") |
| 188 | + |
| 189 | + def listar_libros(self): |
| 190 | + """ |
| 191 | + Muestra una lista de los libros en existencia. |
| 192 | + """ |
| 193 | + if self.registro: |
| 194 | + print("Lista de Libros:") |
| 195 | + for id, nuevo_registro in self.registro.items(): |
| 196 | + titulo = nuevo_registro["titulo"] |
| 197 | + cantidad_copias = nuevo_registro["cantidad_copias"] |
| 198 | + print(f"- {titulo}: {cantidad_copias}") |
| 199 | + else: |
| 200 | + print("No hay libros registrados.") |
| 201 | + |
| 202 | + |
| 203 | +# Uso |
| 204 | +gestor = GestorBiblioteca() |
| 205 | + |
| 206 | +# Registrar libros |
| 207 | +gestor.registro_libros(1, "Cien años de Soledad", "Garcia Marquez", 3, 3) |
| 208 | +gestor.registro_libros( |
| 209 | + 2, "Harry Potter: la píedra filosofal", "Jk Rowling", 3, 3) |
| 210 | +gestor.registro_libros( |
| 211 | + 3, "El señor de los anillos: la comunidad del anillo", "JRR Tolkien", 3, 2) |
| 212 | + |
| 213 | +# Agregar usuario |
| 214 | +gestor. agregar_usuario( 1, "Sofia", 456789, "[email protected]") |
| 215 | +gestor. agregar_usuario( 2, "Juan", 456789, "[email protected]") |
| 216 | + |
| 217 | +# Transaccion |
| 218 | +gestor.prestamo_libro("Cien años de Soledad", "Sofia") |
| 219 | +gestor.prestamo_libro("Cien años de Soledad", "Sofia") |
| 220 | +gestor.prestamo_libro("Cien años de Soledad", "Juan") |
| 221 | +gestor.prestamo_libro( |
| 222 | + "El señor de los anillos: la comunidad del anillo", "Lucas") |
| 223 | +gestor.prestamo_libro("Harry Potter: la píedra filosofal", "Sofia") |
| 224 | +gestor.prestamo_libro("Harry Potter: la píedra filosofal", "Juan") |
| 225 | +gestor.prestamo_libro("Harry Potter: la píedra filosofal", "Juan") |
| 226 | +gestor.prestamo_libro("Harry Potter: la píedra filosofal", "Juan") |
| 227 | +gestor.devolucion_libro("Cien años de Soledad", "Sofia") |
| 228 | +gestor.devolucion_libro("Cien años de Soledad", "Sofia") |
| 229 | + |
| 230 | +# Lista |
| 231 | +gestor.listar_libros() |
| 232 | + |
| 233 | +# Gestor de Biblioteca con SRP |
| 234 | +# Configurar Logger |
| 235 | +logger = logging.getLogger(__name__) |
| 236 | +logger.setLevel(logging.WARNING) |
| 237 | +console_handler = logging.StreamHandler() |
| 238 | +console_handler.setLevel(logging.WARNING) |
| 239 | +console_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') |
| 240 | +console_handler.setFormatter(console_format) |
| 241 | +logger.addHandler(console_handler) |
| 242 | + |
| 243 | + |
| 244 | +class RegistroError(Exception): |
| 245 | + pass |
| 246 | + |
| 247 | + |
| 248 | +class RegistroBiblioteca(): |
| 249 | + def __init__(self): |
| 250 | + self.biblioteca = {} |
| 251 | + self.usuarios = {} |
| 252 | + |
| 253 | + def registro_libros(self, id, titulo, autor, cantidad_copias, max_prestamo): |
| 254 | + logger.debug("Iniciando el registro de un libro.") |
| 255 | + nuevo_libro = { |
| 256 | + "titulo": titulo, |
| 257 | + "autor": autor, |
| 258 | + "cantidad_copias": cantidad_copias, |
| 259 | + "max_prestamo": max_prestamo |
| 260 | + } |
| 261 | + self.biblioteca[id] = nuevo_libro |
| 262 | + logger.info(f"Libro '{titulo}' agregado con éxito.") |
| 263 | + |
| 264 | + def registro_usuario(self, id, nombre, dni, email): |
| 265 | + logger.debug("Iniciando el registro de un usuario.") |
| 266 | + nuevo_usuario = { |
| 267 | + "nombre": nombre, |
| 268 | + "dni": dni, |
| 269 | + "email": email |
| 270 | + } |
| 271 | + self.usuarios[id] = nuevo_usuario |
| 272 | + logger.info(f"Usuario '{nombre}' agregado con éxito.") |
| 273 | + |
| 274 | + def verificacion_registro(self, tipo, titulo_o_nombre): |
| 275 | + logger.debug("Iniciando la verificación de un registro.") |
| 276 | + if tipo == "libro": |
| 277 | + for libro in self.biblioteca.values(): |
| 278 | + if libro["titulo"] == titulo_o_nombre: |
| 279 | + logger.info("Libro registrado") |
| 280 | + return True |
| 281 | + elif tipo == "usuario": |
| 282 | + for usuario in self.usuarios.values(): |
| 283 | + if usuario["nombre"] == titulo_o_nombre: |
| 284 | + logger.info("Usuario registrado") |
| 285 | + return True |
| 286 | + logger.error(f"{tipo.capitalize()} '{titulo_o_nombre}' no registrado") |
| 287 | + return False |
| 288 | + |
| 289 | + |
| 290 | +class TransaccionBiblioteca(): |
| 291 | + """ |
| 292 | + Clase que gestiona las transacciones de prestamo y devolucion de una biblioteca. |
| 293 | + """ |
| 294 | + |
| 295 | + def __init__(self, registro_biblioteca): |
| 296 | + self.registro_biblioteca = registro_biblioteca |
| 297 | + |
| 298 | + def prestamo_libro(self, titulo, nombre): |
| 299 | + logger.debug("Iniciando el prestamo de un libro.") |
| 300 | + try: |
| 301 | + if not self.registro_biblioteca.verificacion_registro("usuario", nombre): |
| 302 | + logger.error(f"Usuario '{nombre}' no está registrado.") |
| 303 | + return |
| 304 | + |
| 305 | + libro_prestado = None |
| 306 | + for id, nuevo_registro in self.registro_biblioteca.biblioteca.items(): |
| 307 | + if nuevo_registro["titulo"] == titulo: |
| 308 | + libro_prestado = nuevo_registro |
| 309 | + logger.info("Coincidencia en la busqueda") |
| 310 | + break |
| 311 | + if libro_prestado: |
| 312 | + if libro_prestado["cantidad_copias"] > 0: |
| 313 | + libro_prestado["cantidad_copias"] -= 1 |
| 314 | + print( |
| 315 | + f"Libro '{titulo}' prestado con éxito a {nombre}.") |
| 316 | + else: |
| 317 | + logger.warning( |
| 318 | + f"Libro '{titulo}' no tiene copias disponibles.") |
| 319 | + else: |
| 320 | + logger.error(f"Libro '{titulo}' no pertenece a la biblioteca.") |
| 321 | + except RegistroError as e: |
| 322 | + print(e) |
| 323 | + |
| 324 | + def devolucion_libro(self, titulo, nombre): |
| 325 | + logger.debug("Iniciando la devoluciòn de un libro.") |
| 326 | + try: |
| 327 | + if not self.registro_biblioteca.verificacion_registro("usuario", nombre): |
| 328 | + logger.error(f"Usuario '{nombre}' no está registrado.") |
| 329 | + return |
| 330 | + |
| 331 | + libro_devuelto = None |
| 332 | + for id, nuevo_registro in self.registro_biblioteca.biblioteca.items(): |
| 333 | + if nuevo_registro["titulo"] == titulo: |
| 334 | + libro_devuelto = nuevo_registro |
| 335 | + logger.info("Coincidencia en la busqueda") |
| 336 | + break |
| 337 | + if libro_devuelto: |
| 338 | + libro_devuelto["cantidad_copias"] += 1 |
| 339 | + print( |
| 340 | + f"Libro '{titulo}' devuelto con éxito por {nombre}.") |
| 341 | + else: |
| 342 | + logger.error(f"Libro '{titulo}' no pertenece a la biblioteca.") |
| 343 | + except RegistroError as e: |
| 344 | + print(e) |
| 345 | + |
| 346 | + |
| 347 | +class Existencias(): |
| 348 | + def __init__(self, registro_biblioteca): |
| 349 | + self.registro_biblioteca = registro_biblioteca |
| 350 | + |
| 351 | + def listar_libros(self): |
| 352 | + """ |
| 353 | + Muestra una lista de los libros en existencia. |
| 354 | + """ |
| 355 | + logger.debug("Recopilando los libros registrados en la biblioteca.") |
| 356 | + if self.registro_biblioteca.biblioteca: |
| 357 | + print("Lista de Libros:") |
| 358 | + for id, nuevo_registro in self.registro_biblioteca.biblioteca.items(): |
| 359 | + titulo = nuevo_registro["titulo"] |
| 360 | + cantidad_copias = nuevo_registro["cantidad_copias"] |
| 361 | + print(f"- {titulo}: {cantidad_copias}") |
| 362 | + else: |
| 363 | + logger.warning("No hay libros registrados.") |
| 364 | + |
| 365 | + |
| 366 | +# Uso |
| 367 | +registro = RegistroBiblioteca() |
| 368 | +transaccion = TransaccionBiblioteca(registro) |
| 369 | +existencias = Existencias(registro) |
| 370 | + |
| 371 | +# Registro libros |
| 372 | +registro.registro_libros(1, "Cien años de Soledad", "Garcia Marquez", 3, 3) |
| 373 | +registro.registro_libros( |
| 374 | + 2, "Harry Potter: la piedra filosofal", "Jk Rowling", 3, 3) |
| 375 | +registro.registro_libros( |
| 376 | + 3, "El señor de los anillos: la comunidad del anillo", "JRR Tolkien", 3, 2) |
| 377 | + |
| 378 | +# Registro usuarios |
| 379 | +registro. registro_usuario( 1, "Sofia", 456789, "[email protected]") |
| 380 | +registro. registro_usuario( 2, "Juan", 456789, "[email protected]") |
| 381 | + |
| 382 | +# Transacciones |
| 383 | +transaccion.prestamo_libro("Cien años de Soledad", "Sofia") |
| 384 | +transaccion.prestamo_libro("Cien años de Soledad", "Sofia") |
| 385 | +transaccion.prestamo_libro("Cien años de Soledad", "Juan") |
| 386 | +transaccion.prestamo_libro("Harry Potter: la piedra filosofal", "Sofia") |
| 387 | +transaccion.prestamo_libro("Harry Potter: la piedra filosofal", "Juan") |
| 388 | +transaccion.devolucion_libro("Cien años de Soledad", "Sofia") |
| 389 | +transaccion.devolucion_libro("Cien años de Soledad", "Sofia") |
| 390 | + |
| 391 | +# Listar libros |
| 392 | +existencias.listar_libros() |
0 commit comments