用Python编写一本书类

时间:2016-12-02 20:14:03

标签: python python-3.x class methods instance-variables

我正在用Python编写一个跟踪一系列书籍的课程。有三个实例变量:authortitlebook_id。有四种方法:

  1. __init__(self, author, title, book_id) :(构造函数;实例化所有实例变量。)
  2. __str__(self):返回此格式的字符串表示形式 Book("Homer", "The Odyssey", 12345)
  3. __repr__(self):返回与__str__
  4. 相同的字符串表示形式
  5. __eq__(self, other)通过检查所有三个实例变量是否相同来确定书本身是否等同于另一本书。返回bool
  6. 我到达了路障。这是我到目前为止的代码,我已经有了一个良好的开端。出于某种原因,我在__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 
    

1 个答案:

答案 0 :(得分:2)

首先,您没有很好地实施方法__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