How does __iter__ work?

前端 未结 5 1085
不知归路
不知归路 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:17

    The specs for def __iter__(self): are: it returns an iterator. So, if self is an iterator, return self is clearly appropriate.

    "Being an iterator" means "having a __next__(self) method" (in Python 3; in Python 2, the name of the method in question is unfortunately plain next instead, clearly a name design glitch for a special method).

    In Python 2.6 and higher, the best way to implement an iterator is generally to use the appropriate abstract base class from the collections standard library module -- in Python 2.6, the code might be (remember to call the method __next__ instead in Python 3):

    import collections
    
    class infinite23s(collections.Iterator):
      def next(self): return 23
    

    an instance of this class will return infinitely many copies of 23 when iterated on (like itertools.repeat(23)) so the loop must be terminated otherwise. The point is that subclassing collections.Iterator adds the right __iter__ method on your behalf -- not a big deal here, but a good general principle (avoid repetitive, boilerplate code like iterators' standard one-line __iter__ -- in repetition, there's no added value and a lot of subtracted value!-).

提交回复
热议问题