Junior — Middle
What is the role of special double underscore methods in implementing iterators in Python?
sobes.tech AI
Answer from AI
In Python, special double underscore methods (so-called dunder methods) play a key role in implementing iterators. To create an iterator in a class, you need to define the following methods:
__iter__(self): returns the iterator itself (usuallyself). This method is called when the object is used in aforloop or with theiter()function.__next__(self): returns the next element in the sequence. When the end of the sequence is reached, it should raise aStopIterationexception.
Example:
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max:
self.current += 1
return self.current
else:
raise StopIteration
for number in CountUpTo(5):
print(number)
Thus, the dunder methods __iter__ and __next__ allow objects to behave as iterators, supporting the iteration protocol in Python.