为什么下面的代码输出 [<__main__.Book 对象在 0x00000207911F1FD0>]。虽然我希望输出我添加的书籍列表



这是一个相当简单的代码,它将图书及其信息添加到列表中。然而,我收到了意想不到的输出。

class Book:
def __init__(self, name, author, code):
self.name = name
self.author = author
self.code = code
self.available = True
class Library:
def __init__(self):
self.books = []
def addBook(self, book):
self.books.append(book)

algebra = Book('Algebra for beginners', 'Albert Einstein', 123)
lib = Library()
lib.addBook(algebra)
print(lib.books)

这里有两种方法:

方法1 -正如forcebru在评论中建议的那样,在Book类中添加一个__repr__方法,它返回一个字符串:

class Book:
def __init__(self, name, author, code):
self.name = name
self.author = author
self.code = code
self.available = True
def __repr__(self):
return self.name+", "+self.author+", code: "+
str(self.code)+", available: "+str(self.available) 

使print(lib.books)的输出为:

[Algebra for beginners, Albert Einstein, code: 123, available: True]

方法2 -在BookLibrary类中添加__str__方法:

class Book:
def __init__(self, name, author, code):
self.name = name
self.author = author
self.code = code
self.available = True
def __str__(self):
return self.name+", "+self.author+", code: "+
str(self.code)+", available: "+str(self.available)
class Library:
def __init__(self):
self.books = []
def __str__(self):
info_string = ""
for b in self.books:
info_string += str(b)+"n"
return info_string
def addBook(self, book):
self.books.append(book)

现在print(lib)的输出是:

Algebra for beginners, Albert Einstein, code: 123, available: True
如您所见,对print()的调用和输出略有不同。

因为类型是Book,后跟它的标识符。如果你想要一些人类可读的东西,使用__repr__(str表示)。

class Book:
def __init__(self, name, author, code):
self.name = name
self.author = author
self.code = code
self.available = True
def __repr__(self):
return f"<{self.__class__.__name__} ({self.name} by {self.author})>"

class Library:
def __init__(self):
self.books = []
def addBook(self, book):
self.books.append(book)
# snake_case for python functions/methods
def search_author(self, author):
books_by_author = [b for b in self.books if b.author == author]
for book in books_by_author:
if book.available:
print(f"Available: Title: {book.name}, code: {book.code}")
else:
print(f"Unavailable: Title: {book.name}, code: {book.code}")
algebra = Book('Algebra for beginners', 'Albert Einstein', 123)
other = Book('Another book by Einstein', 'Albert Einstein', 124)
other.available = False
lib = Library()
lib.addBook(algebra)
lib.addBook(other)
lib.search_author("Albert Einstein")