优化下面的代码,使其更复杂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=[]): 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): for book in self.books: if book.title == title: return book return None def search_book_by_author(self, author): results = [] for book in self.books: if book.author == author: results.append(book) return results def search_book_by_isbn(self, isbn): for book in self.books: if book.isbn == isbn: return book return None 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-03 22:45:41 浏览: 69
优化算法的代码
下面是优化后的代码:
```
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'))
```
主要的优化包括:
1. 将默认参数 books=[] 改为 books=None,并在 __init__ 函数中初始化为一个空列表。这样可以避免多个 Library 实例共享同一个 books 列表的问题。
2. 在 search_book_by_title、search_book_by_author 和 search_book_by_isbn 函数中,使用列表推导式一次性生成结果列表,避免使用 for 循环和 if 语句。
3. 将 if name == 'main': 改为 if __name__ == '__main__':,这是更加 pythonic 的写法。
阅读全文