我想将一个对象添加到列表中,该对象包含标题和艺术家。 该对象添加正常,但是当我想从列表中打印所有对象时,我收到错误。在执行如下所示的方法时,它仅打印最近添加两次的对象。
listOfBooks = []
class Book:
title = "No Title"
author = "No Author"
def myBook(self, title, author):
self.title = title
self.author = author
def get(self):
return self.title + self.author
book = Book()
for _ in range(0,2):
titleInput = input("Enter a title: ")
authorInput = input("Enter an author: ")
book.myBook(titleInput, authorInput)
listOfBooks.append(book)
for i in range(0,len(listOfBooks)):
print(listOfBooks[i].get())
答案 0 :(得分:4)
您需要在每次循环迭代中创建一个新的Book
实例。在循环中移动book = Book()
:
for _ in range(0,2):
book = Book() # Here
titleInput = input("Enter a title: ")
authorInput = input("Enter an author: ")
book.myBook(titleInput, authorInput)
listOfBooks.append(book)
答案 1 :(得分:1)
好的,所以你有一些特定于每个Book
对象的实例变量(标题和作者)。在创建实例时设置这些实例的典型方法是在对象的__init__()
方法中请求它们,因此您的代码将如下所示:
listOfBooks = []
class Book:
title = "No Title"
author = "No Author"
def __init__(self, title, author):
self.title = title
self.author = author
def get(self):
return self.title + self.author
for _ in range(0,2):
titleInput = input("Enter a title: ")
authorInput = input("Enter an author: ")
# Calling the class calls the __init__ method and creates the
# instance
book = Book(titleInput, authorInput)
listOfBooks.append(book)
for i in range(0,len(listOfBooks)):
print(listOfBooks[i].get())
这与余浩的回答结果相同:
Enter a title: Green Eggs
Enter an author: Seuss
Enter a title: Moby Dick
Enter an author: Melville
Green EggsSeuss
Moby DickMelville
答案 2 :(得分:1)
boot initial(book = Book())不在for循环中,因此,实际上,每次循环都编辑同一个Book实例,你可以使用id()来查看。
对于列表,元素可以是相同的,所以关于你的for循环,相同的对象书被附加到listOfBooks两次,这就是为什么打印相同的输出两次。