Help on for loop understanding

Chris Angelico rosuav at gmail.com
Mon Dec 7 22:23:40 EST 2015


On Tue, Dec 8, 2015 at 1:36 PM, Erik <python at lucidity.plus.com> wrote:
> So, you can write your class's iterator to do anything that makes sense when
> someone says "for i in myclassinstance:".
>
> If your class is a subclass of a class ("is-a") that already has a defined
> iterator (such as a list or a dict) and the behaviour of that is correct for
> you, then you need to do nothing (you inherit that class's __iter__()
> method).
>
> If your class should iterate over an embedded object ("has-a") that already
> has a defined iterator, then your __iter__() method can just delegate to
> that object's iterator using something like:
>
> def __iter__(self):
>     return iter(self.embedded_thing)

Another great way to write an __iter__ method is as a generator.

def __iter__(self):
    yield "thing"
    yield from self.things
    yield "other thing"

Like returning an embedded object's iterator, this saves you having to
write a __next__ method. The less work you do, the less bugs you get.

ChrisA



More information about the Python-list mailing list