16

我有这段代码可以创建一个笔记并添加到笔记本中。当我运行它时,我得到一个非序列错误的迭代。

import datetime
class Note:
    def __init__(self, memo, tags):
        self.memo = memo
        self.tags = tags
        self.creation_date = datetime.date.today()

def __str__(self):
    return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)


class NoteBook:
     def __init__(self):
        self.notes = []

     def add_note(self,memo,tags):
        self.notes.append(Note(memo,tags))

if __name__ == "__main__":
    firstnote = Note('This is my first memo','example')
    print(firstnote)
    Notes = NoteBook()
    Notes.add_note('Added thru notes','example-1')
    Notes.add_note('Added thru notes','example-2')
    for note in Notes:
        print(note.memo)

错误:

C:\Python27\Basics\OOP\formytesting>python notebook.py  
Memo=这是我的第一个备忘录,Tag=example  
回溯(最近一次通话最后):  
  文件“notebook.py”,第 27 行,在   
    注意事项中的注意事项:  
TypeError:对非序列的迭代
4

4 回答 4

13

您正在尝试迭代对象本身,这将返回错误。您想遍历对象内部的列表,在这种情况下Notes.notes(这有点令人困惑的命名,您可能希望通过使用笔记本对象实例的另一个名称来区分内部列表)。

for note in Notes.notes:
    print(note.memo)
于 2012-08-08T19:21:54.697 回答
9

Notes 是NoteBook. 要遍历这样的对象,它需要一个__iter__方法

class NoteBook:

    def __iter__(self):
        return iter(self.notes)

PS。Python 中的PEP8建议/约定将小写变量名用于类的实例,将 CamelCase 用于类名。遵循此约定将帮助您立即从您的类中识别您的类实例。

如果您希望遵循此约定(并让喜欢此约定的其他人喜欢自己),请更改Notesnotes.

于 2012-08-08T19:21:28.807 回答
2

如果您想实际迭代 Notes 本身,您还可以添加自定义__iter__ method to it that returns the .notes property.

class Notebook:

    def __iter__(self):
        return iter(self.notes)

    ...
于 2012-08-08T19:23:47.197 回答
1

问题出在一行for note in Notes: ,因为 Notes 是一个对象而不是列表。我相信你想要for note in Notes.notes:

也正如 unutbu 指出的那样,您可以重载__iter__运算符,这将允许您当前的循环工作。这取决于您希望它如何外观。我个人会超载__iter__

于 2012-08-08T19:21:06.157 回答