Iterables
See here.
To create an object/class as an iterator you have to implement the methods __iter__()
and __next__()
to your object. You should probably also add a __init__()
function too to keep track of state.
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.
Example
class MyNumbers:
def __init__(self):
self.a = 2
def __iter__(self):
return self
def __next__(self):
= self.a
x self.a += 1
return x
= MyNumbers()
myclass = iter(myclass)
myiter
for x in myclass:
print(x)
See here for ml example.