Python Design Patterns - Iterator


Advertisements

The iterator design pattern falls under the behavioral design patterns category. Developers come across the iterator pattern in almost every programming language. This pattern is used in such a way that it helps to access the elements of a collection (class) in sequential manner without understanding the underlying layer design.

How to implement the iterator pattern?

We will now see how to implement the iterator pattern.

import time

def fib():
   a, b = 0, 1
   while True:
      yield b
      a, b = b, a + b

g = fib()

try:
   for e in g:
      print(e)
      time.sleep(1)

except KeyboardInterrupt:
   print("Calculation stopped")

Output

The above program generates the following output −

Iterator

If you focus on the pattern, Fibonacci series is printed with the iterator pattern. On forceful termination of user, the following output is printed −

Fibonacci Series

Explanation

This python code follows the iterator pattern. Here, the increment operators are used to start the count. The count ends on forceful termination by the user.

Advertisements