I am trying to understand Iterability in Python.
As I understand, __iter__()
should return an object that has next()
method defined which must return a value or raise StopIteration exception. Thus I wrote this class which satisfies both these conditions.
But it doesnt seem to work. What is wrong?
class Iterator:
def __init__(self):
self.i = 1
def __iter__(self):
return self
def next(self):
self.i += 1
if self.i < 5:
return self.i
else:
raise StopIteration
if __name__ =='__main__':
ai = Iterator()
b = [i for i in ai]
print b
Note: Updated code with incrementing i
in next()
and __main__
in quotes.