尝试使用getBooksByAuthor方法返回名为BookCollection的链表中该作者的所有书籍



具有以下属性的图书对象:标题、作者、年份

class Book():
def __init__(self, title = "", author = "", year = None):
self.title = title
self.author = author
self.year = year
def getTitle(self):
return self.title
def getAuthor(self):
return self.author
def getYear(self):
return self.year
def getBookDetails(self):
string = ("Title: {}, Author: {}, Year: {}"
.format(self.title, self.author, self.year))
return string

名为BookCollection:的链表

class BookCollection():
def __init__(self):
self.head = None
def insertBook(self, book)
temp = BookCollectionNode(book)
temp.setNext(self.head)
self.head = temp

试图归还某作者的所有书籍

def getBooksByAuthor(self, author):
b = Book()
if author == b.getAuthor():
return b.getBookDetails

名为BookCollectionNode:的节点类

class BookCollectionNode():
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newData):
self.data = newData
def setNext(self, newNext):
self.next = newNext

使用以下功能使用getBooksByAuthorMethod:

b0 = Book("Cujo", "King, Stephen", 1981)
b1 = Book("The Shining", "King, Stephen", 1977)
b2 = Book("Ready Player One", "Cline, Ernest", 2011)
b3 = Book("Rage", "King, Stephen", 1977)
bc = BookCollection()
bc.insertBook(b0)
bc.insertBook(b2)
bc.insertBook(b3)
print(bc.getBooksByAuthor("King, Stephen"))

尝试通过使用此方法获取斯蒂芬·金斯的所有书籍。应返回b0b1b3

getBooksByAuthor中存在问题。你为什么要在里面写一本新书?此外,你没有在里面使用self,这意味着你实际上并没有在看你收藏的书。

通常,当你在方法中不使用self时,要么是因为你希望你的方法返回一个常数(这可能发生(,要么是你犯了一个错误。

所以你需要在你收藏的书上循环:

def getBooksByAuthor(self, author):
node = self.head
result = list()  # list of book details with the given author
while node is not None:  # loop on the nodes the collection
book = node.getData()
if book.getAuthor() == author:
result.append(book.getBookDetails())
node = node.getNext()  # move to the next book of the collection
return result

使用修改后的getBooksByAuthor输出(并在集合中添加b1,但您忘记了(:

['Title: Rage, Author: King, Stephen, Year: 1977', 'Title: The Shining, Author: King, Stephen, Year: 1977', 'Title: Cujo, Author: King, Stephen, Year: 1981']

相关内容

  • 没有找到相关文章

最新更新