Take the 2-minute tour × class Square:
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 for i in
Square(1,4):     print i,  Which outputs  1 4 9 16
share|improve this question It "works" in some sense because
it's syntactically valid. Any other definition of "works" relies
on the subjective property of what it's supposed to do. If
you're actually asking How, then perhaps that's what you should
call your question? –  Anon. Jan 13 '10 at 3:15 They're called
iterators. Generally __iter__() returns a separate iterator
object, but this Square class is both the container and the
iterator. See docs.python.org/library/stdtypes.html#iterator-
types If that was your question... –  tclem Jan 13 '10 at 3:16