我正在用 Python 编写一个类,用于跟踪精选的书籍。共有三个实例变量:author
、title
和 book_id
。有四种方法:
__init__(self,author,title,book_id)
:(构造函数;实例化所有实例变量。)__str__(self)
:返回具有此格式的字符串表示形式书籍(“荷马”,“奥德赛”,12345)
__repr__(self)
:返回与__str__
相同的字符串表示形式__eq__(self, other)
通过检查所有三个实例变量是否相同来确定书籍本身是否等同于另一本书。返回一个bool
。
我遇到了障碍。这是到目前为止我已经有了一个良好的开端的代码。由于某种原因,我在 __repr__
方法的返回中不断收到缩进错误。如果熟悉写作类(class)的人有任何建议,我将不胜感激。
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
关于python - 用 Python 编写书籍类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40940161/