2015-02-23 84 views
0

OK所以我创建了两个名为Note和Notebook的类。AttributeError:元组对象没有属性read_note()

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>) 

我将如何解决这个问题不会产生怪异神秘的消息,并打印字符串“首先说明”,“第二注意“和”第三注“。第一季度销售价格指数:

+0

阅读并应用https://stackoverflow.com/help/mcve。删除绒毛​​(.str方法)并包含基本的.add_note方法。然后包含错误消息。 – 2015-02-24 00:18:46

+0

感谢特里我编辑了这篇文章,希望现在更清楚。 – firebird92 2015-02-24 15:42:09

+0

复制,粘贴和运行后,我得到相同的错误。现在我可以回答问题。 – 2015-02-24 23:12:30

回答

0

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

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

notebook1.show_notes()产生什么你似乎想要。第二季度销售价格下降,销售价格下降,第二季度销售价格下降,第二季度销售价格下降。更好的代表性对于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__的行相同。

+0

谢谢你,这是一个非常彻底的答案! – firebird92 2015-02-26 10:52:49

相关问题