Python Define an Iterator Class

Document 对象参考手册Python3 Examples

In Python, an iterator is an object that can remember the position of traversal. Iterator objects start accessing from the first element of the collection until all elements have been accessed. Iterators can only go forward and cannot go backward. To create an iterator class, we need to implement__iter__()and__next__()methods.

Example

class MyIterator:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.end:
            num = self.current
            self.current += 1
            return num
        else:
            raise StopIteration

# Using the iterator
my_iter = MyIterator(1, 5)
for num in my_iter:
    print(num)

Code analysis:

  • __init__Method: Initialize the iterator, set the starting valuestartand end valueend。
  • __iter__Method: Return the iterator object itself, which is part of the iterator protocol.
  • __next__Method: Return the next value of the iterator. If the current value is less than the end value, return the current value and increment it by 1; otherwise, raiseStopIterationexception, indicating the end of iteration.

Output result:

1
2
3
4

Document 对象参考手册Python3 Examples

Other extensions