user198729
user198729

Reputation: 63626

Why the following python code works?

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

Upvotes: 0

Views: 176

Answers (4)

user97370
user97370

Reputation:

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,

Upvotes: 1

Yin Zhu
Yin Zhu

Reputation: 17119

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

Upvotes: 0

RyanWilcox
RyanWilcox

Reputation: 13974

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

Upvotes: 1

John Weldon
John Weldon

Reputation: 40739

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.

Upvotes: 1

Related Questions