[英]Writing a class for books in Python
我正在用Python編寫一個類,該類跟蹤選擇的書籍。 存在三個實例變量: author
, title
和book_id
。 有四種方法:
__init__(self, author, title, book_id)
:(構造函數;實例化所有實例變量。) __str__(self)
:以這種格式返回字符串表示形式Book("Homer", "The Odyssey", 12345)
__repr__(self)
:返回與__str__
相同的字符串表示__str__
__eq__(self, other)
通過檢查所有三個實例變量是否相同來確定書籍本身是否與另一本書相等。 返回bool
。 我到了路障。 到目前為止,這是我有一個良好的開端的代碼。 出於某種原因,我在使用__repr__
方法的返回值時總是遇到縮進錯誤。 如果任何熟悉寫作的人有什么建議,我將不勝感激。
class Book:
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
def __str__(self):
return 'Book(author, title, book_id)'
def __repr__(self):
return 'Book(author, title, book_id)'
def __eq__(self, other):
#Not sure if this is the right approach
for title in Book:
for title in Book:
if title == title:
if author == author:
if book_id == book_id:
return True
首先,您沒有很好地實現__eq__
方法。 其次,您不是,返回的是書中的數據,而是一個字符串'Book(author, title, book_id)'
。 我希望這能解決您的問題。
class Book:
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
def __str__(self):
return 'Book({}, {}, {})'.format(self.author, self.title, self.book_id)
def __repr__(self):
return 'Book({}, {}, {})'.format(self.author, self.title, self.book_id)
def __eq__(self, other):
return self.title == other.title and self.author == other.author and self.book_id == other.book_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.