Despite reading up on it, I still dont quite understand how __iter__
works. What would be a simple explaination?
I've seen def__iter__(self): return self
. I don't see how this works or the steps on how this works.
As simply as I can put it:
__iter__
defines a method on a class which will return an iterator (an object that successively yields the next item contained by your object).
The iterator object that __iter__()
returns can be pretty much any object, as long as it defines a next()
method.
The next
method will be called by statements like for ... in ...
to yield the next item, and next()
should raise the StopIteration
exception when there are no more items.
What's great about this is it lets you define how your object is iterated, and __iter__
provides a common interface that every other python function knows how to work with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With