gpt4 book ai didi

Python 对非序列的迭代

转载 作者:太空狗 更新时间:2023-10-29 16:54:00 24 4
gpt4 key购买 nike

我有这段代码可以创建一个笔记并添加到笔记本中。当我运行它时,我得到一个 Iteration over non-sequence 错误。

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

最佳答案

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

for note in Notes.notes:
print(note.memo)

关于Python 对非序列的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com