Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #100130

Re: Help on for loop understanding

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: Help on for loop understanding
Date 2015-12-08 14:23 +1100
Message-ID <mailman.45.1449545024.12405.python-list@python.org> (permalink)
References (1 earlier) <n45atn$2qs$1@news.albasani.net> <e3bc494d-6a2d-4624-adb2-add96a0f9883@googlegroups.com> <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> <56664210.7040007@lucidity.plus.com>

Show all headers | View raw


On Tue, Dec 8, 2015 at 1:36 PM, Erik <python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:05 -0800
  Re: Help on for loop understanding Robin Koch <robin.koch@t-online.de> - 2015-12-08 02:14 +0100
    Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:31 -0800
      Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:39 -0800
        Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-07 17:50 -0800
          Re: Help on for loop understanding Erik <python@lucidity.plus.com> - 2015-12-08 02:36 +0000
          Re: Help on for loop understanding Chris Angelico <rosuav@gmail.com> - 2015-12-08 14:23 +1100
            Re: Help on for loop understanding Robert <rxjwg98@gmail.com> - 2015-12-08 06:59 -0800
        Re: Help on for loop understanding Erik <python@lucidity.plus.com> - 2015-12-08 01:53 +0000

csiph-web