Implementar una clase de Python para simular un sistema de gestión de libros
Crearemos una clase simple de Python para simular un sistema de gestión de libros. Este sistema permitirá a los usuarios agregar libros, eliminar libros, buscar libros y listar todos los libros. Cada libro contendrá dos atributos: título y autor.
Ejemplo
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
class Library:
def __init__(self):
self.books = []
def add_book(self, title, author):
new_book = Book(title, author)
self.books.append(new_book)
print(f"Added: {new_book}")
def remove_book(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"Removed: {book}")
return
print(f"Book with title '{title}' not found.")
def find_book(self, title):
for book in self.books:
if book.title == title:
print(f"Found: {book}")
return book
print(f"Book with title '{title}' not found.")
return None
def list_books(self):
if not self.books:
print("No books in the library.")
else:
print("Books in the library:")
for book in self.books:
print(book)
# Example usage
library = Library()
library.add_book("1984", "George Orwell")
library.add_book("To Kill a Mockingbird", "Harper Lee")
library.list_books()
library.find_book("1984")
library.remove_book("1984")
library.list_books()
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
class Library:
def __init__(self):
self.books = []
def add_book(self, title, author):
new_book = Book(title, author)
self.books.append(new_book)
print(f"Added: {new_book}")
def remove_book(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"Removed: {book}")
return
print(f"Book with title '{title}' not found.")
def find_book(self, title):
for book in self.books:
if book.title == title:
print(f"Found: {book}")
return book
print(f"Book with title '{title}' not found.")
return None
def list_books(self):
if not self.books:
print("No books in the library.")
else:
print("Books in the library:")
for book in self.books:
print(book)
# Example usage
library = Library()
library.add_book("1984", "George Orwell")
library.add_book("To Kill a Mockingbird", "Harper Lee")
library.list_books()
library.find_book("1984")
library.remove_book("1984")
library.list_books()
Análisis del código:
BookClase: representa un libro, que contiene el título (title) y el autor (author) dos atributos.__str__Método utilizado para devolver la representación de cadena del libro.LibraryClase: representa la biblioteca, que contiene una lista de libros (books). Proporciona los siguientes métodos:add_book(title, author): Agregar un libro a la biblioteca.remove_book(title): Eliminar un libro de la biblioteca según su título.find_book(title): Buscar un libro por su título.list_books(): Listar todos los libros de la biblioteca.
- Uso de ejemplo: crear una
Libraryinstancia, agregar dos libros, listar todos los libros, buscar y eliminar un libro, y finalmente listar todos los libros nuevamente.
Resultado:
Added: 1984 by George Orwell Added: To Kill a Mockingbird by Harper Lee Books in the library: 1984 by George Orwell To Kill a Mockingbird by Harper Lee Found: 1984 by George Orwell Removed: 1984 by George Orwell Books in the library: To Kill a Mockingbird by Harper LeeOtras extensiones
Ejemplos en Python3