tags:

views:

121

answers:

4
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

+1  A: 

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.

John Weldon
It's not a generator, it's an iterator.
Devin Jeanpierre
Thanks Devin. I just read them together, and went with the latter.
John Weldon
+1  A: 

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

RyanWilcox
+1  A: 

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

iter = x.__iter__()         # get iterator
try:
    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

Yin Zhu
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
@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
+1  A: 

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,
Paul Hankin