InterviewHubPRO
Section Overview
Q12

Question 12 of 65

Part 2: Python Core Language, Internals & Runtime (6 - 25)

18%
Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)

The Iterator Protocol:

In Simple Words: An object is an iterator if it implements two dunder methods: __iter__() (returns self) and __next__() (returns next item or raises StopIteration).

python
class Countdown:
    def __init__(self, start):
        self.count = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.count <= 0: raise StopIteration
        val = self.count
        self.count -= 1
        return val

for num in Countdown(3):
    print(num) # 3, 2, 1