Python Define an Iterator Class
In Python, an iterator is an object that remembers its traversal position. An iterator object starts accessing from the first element of a collection and continues until all elements have been accessed. An iterator can only move forward and cannot go backward. To create an iterator class, we need to implement __iter__() and __next__() method.
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 an iterator
my_iter
=
MyIterator
(
1
,
5
)
for
num
in
my_iter:
(
num
)
Code analysis:
__init__method: initialize the iterator, set the start valuestartand the end valueend。__iter__method: returns the iterator object itself, which is part of the iterator protocol.__next__method: returns the next value of the iterator. If the current value is less than the end value, return the current value and increment the current value by 1; otherwise, raiseStopIterationexception to indicate that iteration has ended.
Output result:
1
2
3
4
Python3 Examples