class Book: def __init__(self, title, author, isbn, available=True): self.title = title self.author = author self.isbn = isbn self.available = available class Library: def __init__(self, books=None): if books is None: books = [] self.books = books def add_book(self, book): self.books.append(book) def remove_book(self, book): self.books.remove(book) def search_book_by_title(self, title): return [book for book in self.books if book.title == title] def search_book_by_author(self, author): return [book for book in self.books if book.author == author] def search_book_by_isbn(self, isbn): return [book for book in self.books if book.isbn == isbn] def checkout_book(self, book): if book.available: book.available = False return True else: return False def return_book(self, book): book.available = True if __name__ == '__main__': library = Library() book1 = Book('The Great Gatsby', 'F. Scott Fitzgerald', '978-0143129453') book2 = Book('To Kill a Mockingbird', 'Harper Lee', '978-0446310789') book3 = Book('1984', 'George Orwell', '978-0451524935') library.add_book(book1) library.add_book(book2) library.add_book(book3) print(library.search_book_by_title('1984'))修正优化
时间: 2023-12-06 09:42:24 浏览: 87
python使用 __init__初始化操作简单示例
5星 · 资源好评率100%
class Book:
def __init__(self, title, author, isbn, available=True):
self.title = title
self.author = author
self.isbn = isbn
self.available = available
class Library:
def __init__(self, books=None):
if books is None:
books = []
self.books = books
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def search_book_by_title(self, title):
return [book for book in self.books if book.title.lower() == title.lower()]
def search_book_by_author(self, author):
return [book for book in self.books if book.author.lower() == author.lower()]
def search_book_by_isbn(self, isbn):
return [book for book in self.books if book.isbn == isbn]
def checkout_book(self, book):
if book.available:
book.available = False
return True
else:
return False
def return_book(self, book):
book.available = True
if __name__ == '__main__':
library = Library()
book1 = Book('The Great Gatsby', 'F. Scott Fitzgerald', '978-0143129453')
book2 = Book('To Kill a Mockingbird', 'Harper Lee', '978-0446310789')
book3 = Book('1984', 'George Orwell', '978-0451524935')
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
print(library.search_book_by_title('1984'))
# 修正优化:
# 1. 在搜索图书时,将标题和作者名转换为小写字母,以避免大小写不匹配的问题。
# 2. 在搜索图书时,如果没有找到符合条件的图书,则返回一个空列表,而不是 None。
阅读全文