To create an object/class as an iterator you have to implement the methods __iter__()
and __next__()
to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__()
, which allows you do some initializing when the object is being created.
The __iter__()
method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The __next__()
method also allows you to do operations, and must return the next item in the sequence.
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Try it Yourself ยปTrack your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4