AttributeError:元组对象没有属性read_note()

时间:2015-02-23 23:06:05

标签: python-3.x

好的所以我创建了2个名为Note和Notebook的类。

class Note:
    """ A Note """

    note_number = 1

    def __init__(self, memo="", id=""):
        """ initial attributes of the note"""
        self.memo = memo
        self.id = Note.note_number
        Note.note_number += 1

    def read_note(self):
        print(self.memo)


class NoteBook:
    """The Notebook"""

    def __init__(self):
        self.note_book = []

    def add_notes(self, *args):
        for note in enumerate(args):
            self.note_book.append(note)

    def show_notes(self):
        for note in self.note_book:
            note.read_note()


n1 = Note("First note")
n2 = Note("Second note")
n3 = Note("Third note")

notebook1 = NoteBook()
notebook1.add_notes(n1, n2, n3)
notebook1.show_notes()

Traceback (most recent call last):
  File "C:/Users/Alan/Python3/Random stuff/notebook revisions.py", line 47, in <module>
    notebook1.show_notes()
  File "C:/Users/Alan/Python3/Random stuff/notebook revisions.py", line 38, in show_notes
    note.read_note()
AttributeError: 'tuple' object has no attribute 'read_note'

为什么我会收到属性错误?我希望我的show_notes()方法读取notebook1列表中的所有注释。

此外,如果我打印以下语句,我的结果就是一个神秘的信息:

print(notebook1.note_book[0])


(0, <__main__.Note object at 0x00863F30>)

如何解决这个问题,不会产生奇怪的神秘信息并打印字符串“First note”,“Second note”和“Third note”。

1 个答案:

答案 0 :(得分:0)

Q1。为什么例外?正如我所怀疑的那样,异常是由.add_notes中的错误引起的。 enumerate(args)将注释转换为包含序列号和注释的元组。这是错误的,因为笔记本应该包含注释,而不是元组,因为注释已经有序列号,并且因为每次调用add_note,因此枚举,重新启动为0.将add_note更改为

    def add_notes(self, *args):
        self.note_book.extend(args)

notebook1.show_notes()会产生你想要的东西。

First note
Second note
Third note

Q2。更好的代表?无论元组的内容如何,​​print(notebook1.note_book[0])打印元组都是错误的。对于测试,该行应该是原始脚本的一部分,就在最后一行之前。

打印元组会打印每个元素的repr(),因此将忽略自定义__str__。在add_noted更正后,它现在只打印注释的表示。

<__main__.Note object at 0x00863F30>

要改进这一点,请添加我要求您删除的__str__方法或其版本。不过,我建议您将其命名为__repr__

def __repr__(self):
    """ gives string of initial atrributes"""
    return "Memo: {0}\nNote number: {1}\n ".format(self.memo, self.id)
# Note 1: First note

如果您只定义__str__,那么__repr__仍然是最无用的默认值(如上所述)。如果定义__repr__,则自定义函数将用于repr()和str(),就像在定义后者后添加行__str__ = __repr__一样。