More baby squeaking - iterators in a class

M.E.Farmer mefjr75 at hotmail.com
Fri Dec 31 17:42:34 CET 2004


Terry Reedy wrote:
>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.
Does that mean if you dont't call iter(() on your instance or have a
next() method you can't do this:
> 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')
>>>> for i in p:
>>>>    print i

I am asking because I want to fully understand what makes an
*iterator*. 

M.E.Farmer




More information about the Python-list mailing list