I am learning python iterators and i didnt understand one thing:
class MyNumbers:
def __iter__(self):
self.n = 0
return self
def __next__(self):
self.n =1
return self.n
mynumbers = MyNumbers()
mynum = iter(mynumbers)
print(next(mynum))
print(next(mynum))
print(next(mynum))
print(next(mynum))
print(next(mynum))
Why in def __iter__(self): self.n = 0 return self
we return self? what is it for?
CodePudding user response:
Just like you said, the iter method returns the object itself.
It is what makes an object iterable. So to use a self defined class with iterators, we have to define (override) it.
And the next method returns the number that is increased by 1 at every call.
So when we print the next of "mynum" object consecutively we get the following output:
1
2
3
4
5
For more information, you can research here and here.
CodePudding user response:
According to https://stackoverflow.com/a/40637053, we need __next__()
to actually progress through a sequence of things, and __iter__()
to reset the starting point (for iteration):
The "iterable interface" in python consists of two methods
__next__()
and__iter__()
. The__next__()
function is the most important, as it defines the iterator behavior - that is, the function determines what value should be returned next. The__iter__()
method is used to reset the starting point of the iteration. Often, you will find that__iter__()
can just return self when__init__()
is used to set the starting point.
The documentation should be the go-to for understanding this, https://docs.python.org/3/glossary.html#term-iterator:
Iterators are required to have an
__iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes.
But I don't find that particularly illuminating.
I'd also check to see how Python itself uses __iter__()
, https://github.com/python/cpython/search?q=__iter__.