Skip to content

Commit 1a66529

Browse files
authored
Merge pull request #9058 from barrancus/patch-9
#26 - Python
2 parents a6ca981 + 997aeb4 commit 1a66529

File tree

1 file changed

+395
-0
lines changed

1 file changed

+395
-0
lines changed
Lines changed: 395 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,395 @@
1+
#26 - Python - Principio de Responsabilidad Única (SRP)
2+
# EJERCICIO:
3+
# Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility
4+
# Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento
5+
# de forma correcta e incorrecta.
6+
#
7+
# DIFICULTAD EXTRA (opcional):
8+
# Desarrolla un sistema de gestión para una biblioteca. El sistema necesita
9+
# manejar diferentes aspectos como el registro de libros, la gestión de usuarios
10+
# y el procesamiento de préstamos de libros.
11+
# Requisitos:
12+
# 1. Registrar libros: El sistema debe permitir agregar nuevos libros con
13+
# información básica como título, autor y número de copias disponibles.
14+
# 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con
15+
# información básica como nombre, número de identificación y correo electrónico.
16+
# 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios
17+
# tomar prestados y devolver libros.
18+
# Instrucciones:
19+
# 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje
20+
# los tres aspectos mencionados anteriormente (registro de libros, registro de
21+
# usuarios y procesamiento de préstamos).
22+
# 2. Refactoriza el código: Separa las responsabilidades en diferentes clases
23+
# siguiendo el Principio de Responsabilidad Única.
24+
#
25+
26+
class Counter:
27+
def __iter__(self):
28+
self.a = 1
29+
return self
30+
31+
def __next__(self):
32+
x = self.a
33+
self.a += 1
34+
return x
35+
36+
identifier = iter(Counter())
37+
38+
def separacion(cadena) -> str:
39+
global contador
40+
print(f'\nEjercicio {next(contador)}. {cadena} {'-.-' * 20}')
41+
42+
# Incorrecto
43+
44+
class User:
45+
46+
def __init__(self, name, email) -> None:
47+
self.name = name
48+
self.emmail = email
49+
50+
def save_to_datababase(self):
51+
pass
52+
53+
def send_email(self):
54+
pass
55+
56+
# Correcto
57+
58+
class User:
59+
60+
def __init__(self, name, email) -> None:
61+
self.name = name
62+
self.emmail = email
63+
64+
class UserService:
65+
66+
def save_to_datababase(self, user):
67+
pass
68+
69+
class EmailServie:
70+
71+
def send_email(self, email, message):
72+
pass
73+
74+
75+
# DIFICULTAD EXTRA (opcional):
76+
77+
class Book:
78+
79+
def __init__(self, title: str, author: str, ncopies: int):
80+
self.title = title
81+
self.author = author
82+
self.ncopies = ncopies
83+
self.borrow = 0
84+
85+
def __str__(self):
86+
return f'Libro: {self.title}.\n Autor: {self.author}.\n Número de copias: {self.ncopies}.\n En préstamo: {self.borrow}'
87+
88+
user_lib_id = iter(Counter())
89+
class UserLibrary:
90+
91+
def __init__(self, name: str, email: str):
92+
self.name = name
93+
self.codeid = f'{next(user_lib_id):06}'
94+
self.email = email
95+
self.borrowed = []
96+
97+
def __str__(self):
98+
return f'ID: {self.codeid}\n Nombre: {self.name}.\n Mail: {self.email}\n Libros: {self.borrowed}'
99+
100+
# 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje los tres aspectos mencionados anteriormente (registro de libros, registro de usuarios y procesamiento de préstamos).
101+
class LibraryManagement:
102+
103+
def __init__(self):
104+
self.books = []
105+
self.users = []
106+
107+
def add_book(self, title: str, author: str, ncopies: int | None = 0) -> tuple[bool, str]:
108+
book = self.search_book(title)
109+
if book != None:
110+
if ncopies == 0: ncopies = 1
111+
book.ncopies += ncopies
112+
return True, f'Se añaden {ncopies} copias al listado.'
113+
else:
114+
self.books.append(Book(title, author, ncopies))
115+
return True, f'Libro {title} añadido al catálogo.'
116+
117+
def delete_book(self, title: str) -> tuple[bool, str]:
118+
book = self.search_book(title)
119+
if book != None:
120+
self.books.remove(book)
121+
return True, 'Libro borrado del catálogo.'
122+
else:
123+
return False, 'El libro no existe en el catálogo.'
124+
125+
def search_book(self, search_title: str):
126+
for book in self.books:
127+
if book.title == search_title:
128+
return book
129+
return None
130+
131+
def show_stock(self):
132+
for element in self.books:
133+
print(element)
134+
135+
def borrow_book(self, title: str, inout: bool) -> tuple[bool, str]:
136+
book = self.search_book(title)
137+
if inout:
138+
if book != None:
139+
if book.ncopies >= book.borrow + 1:
140+
book.borrow += 1
141+
return True, 'Libro prestado'
142+
else:
143+
return False, 'No hay libros disponibles'
144+
else:
145+
if book != None:
146+
book.borrow -= 1
147+
return True, 'Libro devuelto'
148+
149+
def add_user(self, name: str, email: str) -> tuple[bool, str]:
150+
user = self.search_user(name)
151+
if user != None:
152+
if name == user.name and email == user.email:
153+
print(user)
154+
return False, 'El usuario ya existe.'
155+
else:
156+
self.users.append(UserLibrary(name, email))
157+
return True, 'Usuario añadido.'
158+
159+
def delete_user(self, name: str) -> tuple[bool, str]:
160+
user = self.search_user(name)
161+
if user != None:
162+
self.users.remove(user)
163+
return True, 'Usuario borrado.'
164+
else:
165+
return False, 'El usuario no existe.'
166+
167+
def search_user(self, search_name: str):
168+
for user in self.users:
169+
if user.name == search_name:
170+
return user
171+
return None
172+
173+
def show_list(self):
174+
for element in self.users:
175+
print(element)
176+
177+
def borrow_book(self, search_name: str, title: str, inout: bool) -> None:
178+
if inout:
179+
user = self.search_user(search_name)
180+
user.borrowed.append(title)
181+
else:
182+
user = self.search_user(search_name)
183+
user.borrowed.remove(title)
184+
185+
# 2. Refactoriza el código: Separa las responsabilidades en diferentes clases siguiendo el Principio de Responsabilidad Única.
186+
class BookManager:
187+
188+
def __init__(self):
189+
self.books = []
190+
191+
def add_book(self, title: str, author: str, ncopies: int | None = 0) -> tuple[bool, str]:
192+
book = self.search_book(title)
193+
if book != None:
194+
if ncopies == 0: ncopies = 1
195+
book.ncopies += ncopies
196+
return True, f'Se añaden {ncopies} copias al listado.'
197+
else:
198+
self.books.append(Book(title, author, ncopies))
199+
return True, f'Libro {title} añadido al catálogo.'
200+
201+
def delete_book(self, title: str) -> tuple[bool, str]:
202+
book = self.search_book(title)
203+
if book != None:
204+
self.books.remove(book)
205+
return True, 'Libro borrado del catálogo.'
206+
else:
207+
return False, 'El libro no existe en el catálogo.'
208+
209+
def search_book(self, search_title: str):
210+
for book in self.books:
211+
if book.title == search_title:
212+
return book
213+
return None
214+
215+
def show_stock(self):
216+
for element in self.books:
217+
print(element)
218+
219+
def borrow_book(self, title: str, inout: bool) -> tuple[bool, str]:
220+
book = self.search_book(title)
221+
if inout:
222+
if book != None:
223+
if book.ncopies >= book.borrow + 1:
224+
book.borrow += 1
225+
return True, 'Libro prestado'
226+
else:
227+
return False, 'No hay libros disponibles'
228+
else:
229+
if book != None:
230+
book.borrow -= 1
231+
return True, 'Libro devuelto'
232+
233+
class UserLibraryManager:
234+
235+
def __init__(self):
236+
self.users = []
237+
238+
def add_user(self, name: str, email: str) -> tuple[bool, str]:
239+
user = self.search_user(name)
240+
if user != None:
241+
if name == user.name and email == user.email:
242+
print(user)
243+
return False, 'El usuario ya existe.'
244+
else:
245+
self.users.append(UserLibrary(name, email))
246+
return True, 'Usuario añadido.'
247+
248+
def delete_user(self, name: str) -> tuple[bool, str]:
249+
user = self.search_user(name)
250+
if user != None:
251+
self.users.remove(user)
252+
return True, 'Usuario borrado.'
253+
else:
254+
return False, 'El usuario no existe.'
255+
256+
def search_user(self, search_name: str):
257+
for user in self.users:
258+
if user.name == search_name:
259+
return user
260+
return None
261+
262+
def show_list(self):
263+
for element in self.users:
264+
print(element)
265+
266+
def borrow_book(self, search_name: str, title: str, inout: bool) -> None:
267+
if inout:
268+
user = self.search_user(search_name)
269+
user.borrowed.append(title)
270+
else:
271+
user = self.search_user(search_name)
272+
user.borrowed.remove(title)
273+
274+
275+
usuarios = [
276+
{"nombre": "Juan Pérez", "email": "juan.perez@example.com"},
277+
{"nombre": "María García", "email": "maria.garcia@test.com"},
278+
{"nombre": "Carlos López", "email": "carlos.lopez@dominio.net"},
279+
{"nombre": "Ana Martínez", "email": "ana.martinez@web.org"},
280+
{"nombre": "Luis González", "email": "luis.gonzalez@example.com"},
281+
{"nombre": "Elena Rodríguez", "email": "elena.rodriguez@test.com"},
282+
{"nombre": "Pedro Sánchez", "email": "pedro.sanchez@dominio.net"},
283+
{"nombre": "Laura Fernández", "email": "laura.fernandez@web.org"},
284+
{"nombre": "Miguel Ramírez", "email": "miguel.ramirez@example.com"},
285+
{"nombre": "Sofía Torres", "email": "sofia.torres@test.com"},
286+
{"nombre": "David Díaz", "email": "david.diaz@dominio.net"},
287+
{"nombre": "Carmen Ruiz", "email": "carmen.ruiz@web.org"},
288+
{"nombre": "Javier Morales", "email": "javier.morales@example.com"}
289+
]
290+
291+
libros = [
292+
{"titulo": "Cien años de soledad", "autor": "Gabriel García Márquez", "cantidad": 2},
293+
{"titulo": "1984", "autor": "George Orwell", "cantidad": 1},
294+
{"titulo": "El Principito", "autor": "Antoine de Saint-Exupéry", "cantidad": 3},
295+
{"titulo": "El Señor de los Anillos", "autor": "J.R.R. Tolkien", "cantidad": 1},
296+
{"titulo": "Don Quijote de la Mancha", "autor": "Miguel de Cervantes", "cantidad": 2},
297+
{"titulo": "Orgullo y Prejuicio", "autor": "Jane Austen", "cantidad": 3},
298+
{"titulo": "Crónica de una muerte anunciada", "autor": "Gabriel García Márquez", "cantidad": 1},
299+
{"titulo": "Crimen y Castigo", "autor": "Fiódor Dostoyevski", "cantidad": 2},
300+
{"titulo": "La Odisea", "autor": "Homero", "cantidad": 3},
301+
{"titulo": "Fahrenheit 451", "autor": "Ray Bradbury", "cantidad": 1},
302+
{"titulo": "El Gran Gatsby", "autor": "F. Scott Fitzgerald", "cantidad": 2},
303+
{"titulo": "En busca del tiempo perdido", "autor": "Marcel Proust", "cantidad": 1},
304+
{"titulo": "El nombre de la rosa", "autor": "Umberto Eco", "cantidad": 3},
305+
{"titulo": "La sombra del viento", "autor": "Carlos Ruiz Zafón", "cantidad": 2},
306+
{"titulo": "Rayuela", "autor": "Julio Cortázar", "cantidad": 1},
307+
{"titulo": "Matar a un ruiseñor", "autor": "Harper Lee", "cantidad": 3},
308+
{"titulo": "Los Miserables", "autor": "Victor Hugo", "cantidad": 2},
309+
{"titulo": "La Metamorfosis", "autor": "Franz Kafka", "cantidad": 1},
310+
{"titulo": "El Retrato de Dorian Gray", "autor": "Oscar Wilde", "cantidad": 3},
311+
{"titulo": "Un mundo feliz", "autor": "Aldous Huxley", "cantidad": 2},
312+
{"titulo": "El Alquimista", "autor": "Paulo Coelho", "cantidad": 1},
313+
{"titulo": "Cumbres Borrascosas", "autor": "Emily Brontë", "cantidad": 3},
314+
{"titulo": "Drácula", "autor": "Bram Stoker", "cantidad": 2},
315+
{"titulo": "El Código Da Vinci", "autor": "Dan Brown", "cantidad": 1},
316+
{"titulo": "Sapiens", "autor": "Yuval Noah Harari", "cantidad": 3},
317+
{"titulo": "La Divina Comedia", "autor": "Dante Alighieri", "cantidad": 2},
318+
{"titulo": "Frankenstein", "autor": "Mary Shelley", "cantidad": 1},
319+
{"titulo": "El viejo y el mar", "autor": "Ernest Hemingway", "cantidad": 3},
320+
{"titulo": "Hamlet", "autor": "William Shakespeare", "cantidad": 2},
321+
{"titulo": "Madame Bovary", "autor": "Gustave Flaubert", "cantidad": 1}
322+
]
323+
324+
def main() -> None:
325+
user_lib_manager = UserLibraryManager()
326+
for element in usuarios:
327+
print(user_lib_manager.add_user(element["nombre"], element["email"]))
328+
book_manager = BookManager()
329+
for element in libros:
330+
print(book_manager.add_book(title=element["titulo"], author=element["autor"], ncopies=element["cantidad"]))
331+
#user_lib_manager.show_list()
332+
#book_manager.show_stock()
333+
while True:
334+
print("\nBienvenido al servicio de gestión de la librería.\nSeleccione la operación a realizar.")
335+
print("1.- Para añadir libro.")
336+
print("2.- Para añadir usuario.")
337+
print("3.- Para sacar un libro.")
338+
print("4.- Para devolver un libro.")
339+
print("5.- Para buscar un libro.")
340+
print("6.- Para buscar un usuario.")
341+
print("7.- Para listar los libros.")
342+
print("8.- Para listar los usuarios.")
343+
print("0.- Para terminar la sesion.")
344+
option = (input("Opcion: ")).strip()
345+
print(option)
346+
347+
match option:
348+
case "1":
349+
title = (input("\nIngrese el título del libro: ")).strip().title()
350+
author = (input("Ingrese el autor del libro: ")).strip().title()
351+
ncopies = (input("Ingrese número de copias: ")).strip()
352+
if ncopies == "":
353+
ncopies = 0
354+
else:
355+
ncopies = int(ncopies)
356+
print(book_manager.add_book(title=title, author=author, ncopies=ncopies))
357+
case "2":
358+
name = (input("\nIngrese el nombre del usuario: ")).strip().title()
359+
email = (input("Ingrese email del usuario: ")).strip()
360+
print(user_lib_manager.add_user(name, email))
361+
case "3":
362+
title = (input("\nIngrese el título del libro: ")).strip().title()
363+
borrowed, mensage = book_manager.borrow_book(title, True)
364+
if borrowed:
365+
name = (input("\nIngrese el nombre del usuario: ")).strip().title()
366+
user_lib_manager.borrow_book(name, title, True)
367+
print(mensage)
368+
else:
369+
print(mensage)
370+
case "4":
371+
title = (input("\nIngrese el título del libro: ")).strip().title()
372+
borrowed, mensage = book_manager.borrow_book(title, False)
373+
if borrowed:
374+
name = (input("\nIngrese el nombre del usuario: ")).strip().title()
375+
user_lib_manager.borrow_book(name, title, False)
376+
print(mensage)
377+
else:
378+
print(mensage)
379+
case "5":
380+
title = (input("\nIngrese el título del libro a buscar: ")).strip().title()
381+
print(book_manager.search_book(search_title=title))
382+
case "6":
383+
name = (input("\nIngrese el nombre del usuario: ")).strip().title()
384+
print(name)
385+
print(user_lib_manager.search_user(search_name=name))
386+
case "7":
387+
book_manager.show_stock()
388+
case "8":
389+
user_lib_manager.show_list()
390+
case "0":
391+
print("\nHasta la próxima.")
392+
break
393+
394+
if __name__ == '__main__':
395+
main()

0 commit comments

Comments
 (0)