Implement a Python class to simulate a library management system

Document 对象参考手册Python3 Examples

We will create a simple Python class to simulate a library management system. This system will allow users to add books, delete books, find books, and list all books. Each book will have two attributes: title and author.

Example

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()

Code explanation:

  1. BookClass: Represents a book, containing title (title) and author (author) two attributes.__str__Method for returning the string representation of a book.
  2. LibraryClass: Represents a library, containing a list of books (books). Provides the following methods:
    • add_book(title, author): Add a book to the library.
    • remove_book(title): Delete a book from the library based on the title.
    • find_book(title): Find a book based on the title.
    • list_books(): List all books in the library.
  3. Example usage: Create aLibraryinstance, add two books, list all books, find and delete a book, then list all books again.

Output result:

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 Lee

Document 对象参考手册Python3 Examples

Other extensions