Junior — Middle
What functions need to be implemented to create your own iterator in a class?
sobes.tech AI
Answer from AI
To create a custom iterator in a Python class, you need to implement two methods:
__iter__(self)— should return the iterator object. Usually, this is the object itself if it implements the__next__method.__next__(self)— returns the next element in the sequence. When the sequence ends, it should raise aStopIterationexception.
Example implementation of an iterator in a class:
class MyRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
val = self.current
self.current += 1
return val
for i in MyRange(1, 4):
print(i) # Will output 1, 2, 3
Thus, the class becomes an iterable object that can be used in for loops and other contexts expecting an iterator.