How to implement __iter__(self) for a container object (Python)

后端 未结 9 1971
甜味超标
甜味超标 2020-12-02 08:00

I have written a custom container object.

According to this page, I need to implement this method on my object:

__iter__(self)

Howe

9条回答
  •  星月不相逢
    2020-12-02 08:20

    I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.

    The following will create an iterator that yields five, and then every item in some_list.

    def __iter__(self):
       yield 5
       yield from some_list
    

    Pre-3.3, yield from didn't exist, so you would have to do:

    def __iter__(self):
       yield 5
       for x in some_list:
          yield x
    

提交回复
热议问题