Iterator: a counter

We can create a iterator using a class. We are required to implement the __iter__ method that returns the iterator object and the __next__ method that returns the next element in our iteration. We can indicated that the iteration was exhaused by raising a StopIteration exception.

The instance-object that is created from this class-object is the iterator, not the class-object itself!

class Counter():
   def __init__(self):
       self.count = 0

   def __iter__(self):
       return self

   def __next__(self):
       self.count += 1
       if self.count > 3:
           raise StopIteration
       return self.count