实现一个 Python 类来模拟图书管理系统
我们将创建一个简单的 Python 类来模拟图书管理系统。这个系统将允许用户添加书籍、删除书籍、查找书籍以及列出所有书籍。每本书将包含书名和作者两个属性。
实例
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()
代码解析:
Book
类:表示一本书,包含书名 (title
) 和作者 (author
) 两个属性。__str__
方法用于返回书籍的字符串表示。Library
类:表示图书馆,包含一个书籍列表 (books
)。提供了以下方法:add_book(title, author)
:添加一本书到图书馆。remove_book(title)
:根据书名从图书馆中删除一本书。find_book(title)
:根据书名查找一本书。list_books()
:列出图书馆中的所有书籍。
- 示例用法:创建一个
Library
实例,添加两本书,列出所有书籍,查找并删除一本书,最后再次列出所有书籍。
输出结果:
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