這是一個相當簡單的代碼,可將書籍及其資訊添加到串列中。然而我收到了意外的輸出。
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)
uj5u.com熱心網友回復:
有兩種方法可以到這里:
方法 1 - asForceBru 在評論中建議,__repr__在Book類中添加一個方法,該方法回傳一個字串:
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 -__str__向Book 和 Library類添加一個方法:
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()和輸出略有不同。
uj5u.com熱心網友回復:
因為型別是 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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337520.html
