Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does __iter__ work?

Tags:

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.

like image 725
sss Avatar asked Oct 22 '09 22:10

sss


1 Answers

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.

like image 172
Gabriel Hurley Avatar answered Sep 18 '22 14:09

Gabriel Hurley