Python迭代非序列

use*_*619 16 python

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

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)
Run Code Online (Sandbox Code Playgroud)

错误:

C:\Python27\Basics\OOP\formytesting>python notebook.py  
Memo=This is my first memo, Tag=example  
Traceback (most recent call last):  
  File "notebook.py", line 27, in   
    for note in Notes:  
TypeError: iteration over non-sequence

pk-*_*-nb 12

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

for note in Notes.notes:
    print(note.memo)
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 9

Notes是一个实例NoteBook.要迭代这样的对象,它需要一个__iter__方法:

class NoteBook:

    def __iter__(self):
        return iter(self.notes)
Run Code Online (Sandbox Code Playgroud)

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

如果您希望遵循此惯例(并且喜欢喜欢此约定的其他人),请Notes转到notes.