Junior — Middle
What specific methods need to be implemented to create your own iterator object?
sobes.tech AI
Answer from AI
To create a custom iterator object in Python, you need to implement two special methods:
-
__iter__(self)— should return the iterator object itself. This allows the object to be used in loops and other constructs expecting an iterator. -
__next__(self)— returns the next element in the sequence. When the end of the sequence is reached, it should raise aStopIterationexception.
Here's an example of a simple iterator that returns numbers from 1 to 3:
class MyIterator:
def __init__(self):
self.current = 1
self.max = 3
def __iter__(self):
return self
def __next__(self):
if self.current <= self.max:
val = self.current
self.current += 1
return val
else:
raise StopIteration
# Usage
for num in MyIterator():
print(num)