How does __iter__ work?

前端 未结 5 1176
不知归路
不知归路 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 02:54

    An iterator needs to define two methods: __iter__() and __next__() (next() in python2). Usually, the object itself defines the __next__() or next() method, so it just returns itself as the iterator. This creates an iterable that is also itself an iterator. These methods are used by for and in statements.

    • Python 3 docs: docs.python.org/3/library/stdtypes.html#iterator-types

    • Python 2 docs: docs.python.org/2/library/stdtypes.html#iterator-types

提交回复
热议问题