python - 用 Python 编写书籍类

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

我正在用 Python 编写一个类,用于跟踪精选的书籍。共有三个实例变量:authortitlebook_id。有四种方法:

  1. __init__(self,author,title,book_id):(构造函数;实例化所有实例变量。)
  2. __str__(self):返回具有此格式的字符串表示形式 书籍(“荷马”,“奥德赛”,12345)
  3. __repr__(self):返回与 __str__ 相同的字符串表示形式
  4. __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/

相关文章:

python - 根据多个标准进行选择

python - plumbum.commands.processes.ProcessExecutionError : for commands which return null

python-3.x - 使用规则在主页面完成后抓取 'next' 页面

python - 在 matplotlib 上设置高度和宽度

c# - Datagridview 显示类名而不是属性

python - Python中类之间的通信

使用 15000 行数据集查找最小列值的 Python 代码

python - 将基于 OpenCV 的 C++ 函数与 Mat/Numpy 转换为 Python 公开

python - PyQt5 QDialog在后续线程中

c++ - 用户定义的类构造函数和函数不起作用,我是否错误地构造了我的类?