How to Create an Object/class As an Iterator in Python


In this example we will show how to create an object/class as an iterator in Python.

Source Code

class MySquare:
    def __init__(self, x):
        self.x = x

    def __iter__(self):
        return self

    def __next__(self):
        self.x = self.x ** 2
        return self.x


my_square = MySquare(2)
my_iter = iter(my_square)

print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))

Output:

4
16
256
65536
4294967296
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments