What makes an iterator an iterator?

Stefan Rank list-ener at strank.info
Wed Apr 18 03:46:53 EDT 2007


on 18.04.2007 07:39 Steven D'Aprano said the following:
> I thought that an iterator was any object that follows the iterator

replace object with "instance of a class", i.e. the relevant methods are 
looked up in the __class__ not in the instance (I think).
I had the same troubles trying to dynamically reassign a __call__ method...

> protocol, that is, it has a next() method and an __iter__() method.
> 
> But I'm having problems writing a class that acts as an iterator. I have:
> 
> class Parrot(object):
>     def __iter__(self):
>         return self
>     def __init__(self):
>         self.next = self._next()
>     def _next(self):
>         for word in "Norwegian Blue's have beautiful plumage!".split():
>             yield word

Try this::

  class Parrot(object):
      def __iter__(self):
          return self
      def __init__(self):
          self.__class__.next = self._next().next # see post by I V
      def _next(self):
          for word in "Norwegian Blue's have beautiful plumage!".split():
              yield word

This works but practically forces the class to be used as a singleton... 
not very helpful :)

Better:

* use the '__iter__ returns/is a generator' way,
* or if you need the object to be the iterator, implement the next 
method directly on the class::

  class Parrot(object):
      def _next(self):
          for word in "Norwegian Blue's have beautiful plumage!".split():
              yield word
      def __iter__(self):
          self.generator = self._next()
          return self
      def next(self):
          return self.generator.next()

cheers,
stefan




More information about the Python-list mailing list