More baby squeaking - iterators in a class
Steven Bethard
steven.bethard at gmail.com
Fri Dec 31 11:31:45 EST 2004
Bulba! wrote:
>
> 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()
>
[snip]
>
> 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')
>
[snip]
>
>>>>o.next()
> 's'
Note the difference here. When you're using the function, you call the
iter function (called rev in your example). When you're using the
class, you haven't called the iter function, only instantiated the class
(i.e. called the __init__ function). Try one of the following:
py> p = R3('eggs')
py> i = p.__iter__()
py> i.next()
's'
or
py> p = R3('eggs')
py> i = iter(p)
py> i.next()
's'
Steve
More information about the Python-list
mailing list