iter & next
Python 2
  • __iter__ and next, called by iter() and next()
  • #!/usr/bin/python
    class MyRange:
        def __init__(self, m = 0):
            self.max = m
            self.n = 0
     
        def __iter__(self):
            print('Call __iter__ ...')
            self.n = 0
            return self
     
        def next(self):
            print('Call __next__ ...')
            if self.n <= self.max:
                result = 2 ** self.n
                self.n += 1
                return result
            else:
                raise StopIteration
     
    def main():
        l = iter(MyRange(4)) # __iter__
        while True:
            try:
                print(l.next()) # next
            except StopIteration, err:
                print(err)
                break
     
    if __name__ == '__main__':
        main();
    	
    		
    Python 3
  • __iter__ and __next__, called by iter() and next()
  • #!/usr/bin/python
    class MyRange:
        def __init__(self, m = 0):
            self.max = m
            self.n = 0
    
        def __iter__(self):
            print('Call __iter__ ...')
            self.n = 0
            return self
    
        def __next__(self):
            print('Call __next__ ...')
            if self.n <= self.max:
                result = 2 ** self.n
                self.n += 1
                return result
            else:
                raise StopIteration('End of iteration ...')
     
    def main():
        l = iter(MyRange(4))
        while True:
            try:
                print(next(l))
            except StopIteration as err:
                print(err)
                break
    
    if __name__ == '__main__':
        main();