__iter__()` and `__next__()` methods in a class. The `__iter__()` method returns the iterator object itself. __next__()` method returns the next value from the iterator. Here's an example program that demonstrates how to create an iterator :class MyIterator:
def __init__(self, max_num):
self.max_num = max_num
self.current_num = 0
def __iter__(self):
return self
def __next__(self):
if self.current_num < self.max_num:
self.current_num += 1
return self.current_num
else:
raise StopIteration
# create an iterator object
my_iterator = MyIterator(5)
# loop through the iterator
for num in my_iterator:
print(num)1
2
3
4
5MyIterator` that implements the `__iter__()` and `__next__()` methods. The `__init__()` method initializes the maximum number of values that can be returned by the iterator and the current number that is being returned. __iter__()` method returns the iterator object itself, and the `__next__()` method returns the next value from the iterator until the maximum number is reached. StopIteration` exception is raised to indicate that the iterator is done. We create an instance of the `MyIterator` class with a maximum of 5 numbers and then loop through the iterator to print each number.