Python iteration over non-sequence

后端 未结 4 1145
温柔的废话
温柔的废话 2021-01-04 01:16

I have this piece of code which creates a note and adds to the notebook. When I run this I get a Iteration over non-sequence error.

import datetime
class Not         


        
相关标签:
4条回答
  • 2021-01-04 01:48

    You are trying to iterate over the object itself, which is returning the error. You want to iterate over the list inside the object, in this case Notes.notes (which is somewhat confusing naming, you may want to distinguish the internal list by using another name for the instance of the notebook object).

    for note in Notes.notes:
        print(note.memo)
    
    0 讨论(0)
  • 2021-01-04 01:59

    Notes is an instance of NoteBook. To iterate over such an object, it needs an __iter__ method:

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

    PS. It is a PEP8 recommendation/convention in Python to use lowercase variable names for instances of classes, and CamelCase for class names. Following this convention will help you instantly recognize your class instances from your classes.

    If you wish to follow this convention (and endear yourself to others who like this convention), change Notes to notes.

    0 讨论(0)
  • 2021-01-04 02:04

    If you wanted to actually iterate Notes itself, you could also add a custom __iter__ method to it that returns the .notes property.

    class Notebook:
    
        def __iter__(self):
            return iter(self.notes)
    
        ...
    
    0 讨论(0)
  • 2021-01-04 02:06

    The problem is in the line for note in Notes: since Notes is an object not a list. I believe you want for note in Notes.notes:

    also as unutbu pointed out, you can overload the __iter__ operator which will allow your current loop to work. It depends how you want this to outwardly appear. Personally I would overload __iter__

    0 讨论(0)
提交回复
热议问题