How does __iter__ work?

前端 未结 5 1063
不知归路
不知归路 2021-02-04 02:17

Despite reading up on it, I still dont quite understand how __iter__ works. What would be a simple explaination?

I\'ve seen def__iter__(self): retu

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 03:04

    As simply as I can put it:

    __iter__ defines a method on a class which will return an iterator (an object that successively yields the next item contained by your object).

    The iterator object that __iter__() returns can be pretty much any object, as long as it defines a next() method.

    The next method will be called by statements like for ... in ... to yield the next item, and next() should raise the StopIteration exception when there are no more items.

    What's great about this is it lets you define how your object is iterated, and __iter__ provides a common interface that every other python function knows how to work with.

提交回复
热议问题