"Bulba!" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> "Define a __iter__() method which returns an object with a next()
> method. If the class defines next(), then __iter__() can just return
> self:"
>
> The thing is, I tried to define __iter__() directly without explicit
> defining next (after all, the conclusion from this passage should
> be that it's possible).
It is, see below.
> 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]
Change 'return' to 'yield'. Then r.__iter__() *will* return a
(generator)iterator with a .next method, as required. But it will only
yield one value before running off the end. Since __iter__ is meant to be
called only once, you need to loop explicitly in the generator. For
instance
def __iter__(self):
i,d = self.i, self.d
while i
i =- 1
yield d[i]
Copying i makes the generator non-destuctive.
(PS, use spaces, not tabs, in posted code.)
Terry J. Reedy
--
http://mail.python.org/mailman/listinfo/python-list