More baby squeaking - iterators in a class

Terry Reedy tjreedy at udel.edu
Fri Dec 31 11:17:29 EST 2004


"Bulba!" <bulba at bulba.com> wrote in message 
news:bvaat0pq3ruq789dfl4fpe0mg4jd2of2qn at 4ax.com...
> 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')
>>>> p.next()

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 ip.next and ip.next() 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