Thursday, November 8, 2012

Iterator in python

You can make any class in a python utterable using iterator.
class IterTest:
    def __init__(self, itemList):
        self.itemList = itemList
        self.reset()

    def __iter__(self):
        return self
        
    def next(self):
        try:
            result = self.itemList[self.index]
        except IndexError:
            raise StopIteration
        self.index += 1
        return result       
        
    def reset(self):
        self.index = 0
        
        
if __name__ == "__main__":
    iterTest = IterTest([[1,3], [2,4]])
    for item in iterTest:
        print item
        
    iterTest.reset()
    for item in iterTest:
        print item      

References

No comments:

Post a Comment