More baby squeaking - iterators in a class
mefjr75 at hotmail.com
Sat Jan 1 02:47:55 EST 2005
py> from __future__ import generators
I was thinking about the __iter__ and what you were saying about
generators, so I opened up pyshell and started typing.
py> class R3:
... def __init__(self, d):
... def __iter__(self):
... d,i = self.d, self.i
... while i>0:
... yield d[i]
py> r = R3('qwerty')
<class __main__.R3 at 0x01440A38>
<bound method R3.__iter__ of <__main__.R3 instance at 0x0141BFB0>>
<stackless.generator object at 0x0143FE38>
py> a = r.__iter__()
Traceback (most recent call last):
File "<input>", line 1, in ?
Doh! ok now I get it __iter__ RETURNS a generator ;)
It seems so obvious now I look at it.
Sometimes I am a bit slow to catch on , but I never forget, much.
Deeper down the rabbit hole.
> Terry ,
> Thank you for the explanation . That is much clearer now, I have
> a bit with generators but have never tried to create a custom
> I am just now getting into the internals part of python objects...
> langauage is still amazing to me!
> The reason I asked the question was because I tried that code I
> and it worked fine in python2.2.3 ?
> >Ignoring the older iteration method based on __getitem__, which I
> >you do ignore, yes, you cannot do that.
> py>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]
> py>a = R3('qwerty')
> ['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']
> py>for i in a:
> ... print i
> Ok I don't see __getitem__ anywhere in this object.
> Still scratchin my head? Why does this work?
More information about the Python-list