More baby squeaking - iterators in a class

Bulba! bulba at bulba.com
Fri Dec 31 11:46:09 CET 2004


On Thu, 30 Dec 2004 12:06:31 -0800, Scott David Daniels
<Scott.Daniels at Acm.Org> wrote:

>Here's one way:  # (Make __iter__ an iterator)
>Py> class R1(object):
>         def __init__(self, data):
>             self.data = data
>             self.i = len(data)
>         def __iter__(self):
>             while self.i > 0:
>                 self.i -= 1
>                 yield self.data[self.i]

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()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: R3 instance has no attribute 'next'
>>> dir(p)
['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']
>>> list(p)
['s', 'g', 'g', 'e']
>>> 

I tried all the methods advised by you and other posters and they do
return an object with __iter__, but not with the next method.

What's strange is that when it comes to function, it does return
the .next method:

def rev(d):
    for i in range (len(d)-1, -1, -1):
        yield d[i]
        
>>> o=rev('eggs')
>>> o
<generator object at 0x0120DF58>
>>> dir(o)
['__class__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__iter__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'gi_frame',
'gi_running', 'next']
>>> o.next()
's'
>>> o.next()
'g'
>>> o.next()
'g'
>>> o.next()
'e'


The function returns 'generator object', as shown above, 
while p is a class instance:

>>> p
<__main__.R3 instance at 0x0123CA58>




--
It's a man's life in a Python Programming Association.



More information about the Python-list mailing list