[Tutor] __iter__

Christopher Spears cspears2002 at yahoo.com
Mon Jan 16 21:50:14 CET 2006


I'm not sure if I understand __iter__.  You use it to
create an object that iterates through itself using a
next menthod ?

class Squares:
        def __init__(self, start, stop):
                self.value = start - 1
                self.stop = stop
        def __iter__(self):
                return self
        def next(self):
                if self.value == self.stop:
                        raise StopIteration
                self.value += 1
                return self.value ** 2

>>> from iters import Squares
>>> for i in Squares(1, 5):
...     print i,
...
1 4 9 16 25


"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton


More information about the Tutor mailing list