How Do You Create a Class That Is an Iterator in Python?

Problem scenario
You want to implement an object that is an iterator in Python. What do you do to implement iterator behavior in the class?

Solution
Run this program as an example:

class Computation:

    def __init__(self, max = 0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max:
            product = 2 * self.n
            self.n += 1
            return product

objecta = Computation(4) # The number must be 3 or greater if you want to print something other than "None" with this program. 
variter1 = iter(objecta)
next(variter1)
next(variter1)
next(variter1)
pf = next(variter1)
print(pf)

Leave a comment

Your email address will not be published. Required fields are marked *