More baby squeaking - iterators in a class

M.E.Farmer mefjr75 at hotmail.com
Fri Dec 31 09:46:33 EST 2004


Reread Russel Blau post he is spot on with his comments:
Russel Blau wrote:
>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
That works exactly as advertised.

py> s = R('54645656')
... s.next()
'6'
... s.next()
'5'
... s.next()
'6'
... s.next()
'5'
... s.next()
'4'
.. s.next()
'6'
... s.next()
'4'
... s.next()
'5'
... s.next()
Traceback (most recent call last):
File "<input>", line 1, in ?
File "<input>", line 7, in next
StopIteration

And the other posters showed you how to create an iterator without a
next() .
Other than having no next() method they still work the same.




More information about the Python-list mailing list