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 doesn't seem to work. What is wrong?
class Iterator:
    def __init__(self):
        self.i = 1
    def __iter__(self):
        return self
    def next(self):
        if self.i < 5:
            return self.i
        else:
            raise StopIteration
if __name__ == __main__:
    ai = Iterator()
    b  = [i for i in ai]
    print b
                Your Iterator class is correct. You just have a typo in this statement:
if __name__ ==' __main__':
There's a leading whitespace in the ' __main__' string. That's why your code is not executed at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With