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
add comment

4 Answers

up vote 0 down vote accepted

The typical Python iteration protocol: for y in x... is as follows:

iter = x.__iter__()         # get iterator
    while 1:
        y = iter.next()         # get each item
        ...                     # process y
except StopIteration: pass  # iterator exhausted

from http://www.boost.org/doc/libs/1_41_0/libs/python/doc/tutorial/doc/html/python/iterators.html

share|improve this answer
Eck. it should be it=iter(x) . Don't shadow builtins (don't assign to a variable called iter, map, int, etc.), and don't call __special__ methods directly except in extraordinary circumstances (such as when you are overriding and need to call on the parent). Also, you should probably explain the relation to a for loop more clearly. Oh, looks like you plagiarized the source. Nevermind. Write your own answer. –  Devin Jeanpierre Jan 13 '10 at 3:19
@Devin good point! but i think the asker wants the direct answer, so I just attach the direct answer with losing some good style.. –  Yin Zhu Jan 13 '10 at 3:22
add comment

why wouldn't it? It looks like a normal iterator to me...

the next() method is a 'known' method in python that along with the __iter__() method signals a generator.

Here is the python docs on iterators.

share|improve this answer
It's not a generator, it's an iterator. –  Devin Jeanpierre Jan 13 '10 at 3:17
Thanks Devin. I just read them together, and went with the latter. –  John Weldon Jan 13 '10 at 3:19
add comment

This is a Python iterator: every time through the loop the next() method is called

share|improve this answer
add comment

It's an iterator.

Normally though, you would write it using yield.

def Square(start, stop):
    for value in xrange(start, stop + 1):
        yield value ** 2

for i in Square(1, 4):
    print i,
share|improve this answer
add comment

Your Answer


