为 Python 中的书籍写一篇 class

Writing a class for books in Python

我正在 Python 中编写一个 class 来跟踪精选书籍。共有三个实例变量:authortitlebook_id。有四种方法:

  1. __init__(self, author, title, book_id):(构造函数;实例化所有实例变量。)
  2. __str__(self): returns 这种格式的字符串表示 Book("Homer", "The Odyssey", 12345)
  3. __repr__(self): returns 与 __str__
  4. 相同的字符串表示
  5. __eq__(self, other) 通过检查所有三个实例变量是否相同来确定书籍本身是否等同于另一本书。 Returns一个bool.

我遇到了障碍。这是我到目前为止的代码,我已经有了一个良好的开端。出于某种原因,我不断收到 __repr__ 方法的 return 的缩进错误。如果任何熟悉写作 classes 的人有任何建议,我将不胜感激。

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