Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Define an Iterator Class

Python Define an Iterator Class

Document Object Reference Manual Python3 Examples

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:

   

print

(

num

)

Code analysis:

Output result:

1
2
3
4

Document Object Reference Manual Python3 Examples