More baby squeaking - iterators in a class

Russell Blau russblau at hotmail.com
Thu Dec 30 19:05:43 CET 2004


"Bulba!" <bulba at bulba.com> wrote in message
news:njf8t09i9injk8cr7r1858ng4gkq6fu5o6 at 4ax.com...
> Hello Mr Everyone,
>
> From:
> http://docs.python.org/tut/node11.html#SECTION0011900000000000000000
>
> "Define a __iter__() method which returns an object with a next()
> method. If the class defines next(), then __iter__() can just return
> self:"
>
> The thing is, I tried to define __iter__() directly without explicit
> defining next (after all, the conclusion from this passage should
> be that it's possible).

I don't get that from the passage quoted, at all, although it is somewhat
opaque.  It says that your __iter__() method must *return an object* with a
next() method; your __iter__() method below doesn't return such an object,
but instead returns a string.  It then says that *if* your class defines
next(), which yours doesn't, __iter__() can return self.

[spaces inserted; you should note that many newsreaders strip the TAB
character...]

> class R:
>   def __init__(self, d):
>     self.d=d
>     self.i=len(d)
>   def __iter__(self):
>     if self.i == 0:
>       raise StopIteration
>     self.i -= 1
>     return self.d[self.i]
>

Solution:  replace "__iter__" with "next" in the class definition above,
then add to the end:

   def __iter__(self):
     return self


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list