Help on for loop understanding

Robert rxjwg98 at gmail.com
Tue Dec 8 09:59:56 EST 2015


On Monday, December 7, 2015 at 10:24:09 PM UTC-5, Chris Angelico wrote:
> On Tue, Dec 8, 2015 at 1:36 PM, Erik <pylucidity.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

Thanks. One more question is here. I see the following code snippet. 
It can run as expected. That is, zeros array is iterable, but I don't see
the iterator of it. And I do see some codes using np.nditer, but the 
following without it.


seq = [ im for im in zeros((20,240,320), int)]

1. What difference for iterate with and without np.nditer?
2. How can I know one object whether it is iterable (only by testing?)




More information about the Python-list mailing list