python
class Book:
def __init__(self,title,author,year):
self.title = title
self.author = author
self.year = year
class Library:
def __init__(self):
self.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):
found_books = []
for book in self.books:
if book.author == author:
found_books.append(book)
return found_books
# 示例使用
library = Library()
book1 = Book("Python Crash Course", "Eric Matthes", 2016)
book2 = Book("Clean Code", "Robert C.Martin", 2008)
book3 = Book("The Pragmatic Programmer", "Andrew Hunt,David Thomas", 1999)
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
search_title = "Clean Code"
found_book = library.search_book_by_title(search_title)
if found_book:
print("找到了书籍:", found_book.title)
else:
print("未找到书籍:", search_title)
search_author = "Robert C.Martin"
found_books = library.search_book_by_author(search_author)
if found_books:
print("找到了以下作者的书籍:")
for book in found_books:
print(book.title)
else:
print("未找到作者:", search_author)
标签:search,author,python,self,title,book,books From: https://blog.51cto.com/u_16058927/7159818