More baby squeaking - iterators in a class

Terry Reedy tjreedy at
Fri Dec 31 17:17:29 CET 2004

"Bulba!" <bulba at> wrote in message 
news:bvaat0pq3ruq789dfl4fpe0mg4jd2of2qn at
> Thanks to everyone for their responses, but it still doesn't work re
> returning next() method:
> class R3:
>    def __init__(self, d):
>        self.d=d
>        self.i=len(d)
>    def __iter__(self):
>        d,i = self.d, self.i
>        while i>0:
>            i-=1
>            yield d[i]
>>>> p=R3('eggs')

This is the wrong test for what I and some others thought you were asking. 
The requirement for p to be an *iterable* and useable in code such as 'for 
i in p' is that iter(p), not p itself, have a .next method, and iter(p) 
will.  Try ip=iter(p) followed by and instead.

If, for whatever reason, you instead want p to actually be an *iterator* 
with a .next (or .getitem) method, then, of course, you have to actually 
give it a .next (or .getitem) method.

Terry J. Reedy

More information about the Python-list mailing list