User-Defined Iterators : iter « Class « Python Tutorial






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


for i in Squares(1, 5):                
    print i,








11.21.iter
11.21.1.Iterators
11.21.2.Make a new iterator object for each new iteration
11.21.3.User-Defined Iterators