More baby squeaking - iterators in a class

M.E.Farmer mefjr75 at hotmail.com
Fri Dec 31 22:06:37 EST 2004


Terry ,
Thank you for the explanation . That is much clearer now, I have played
a bit with generators but have never tried to create a custom iterator.
I am just now getting into the internals part of python objects... this
langauage is still amazing to me!
The reason I asked the question was because I tried that code I posted
and it worked fine in python2.2.3 ?

>Ignoring the older iteration method based on __getitem__, which I
recommend
>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')
py>dir(a)
['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']
py>for i in a:
...     print i
...
y
t
r
e
w
q
Ok I don't see __getitem__  anywhere in this object.
Still scratchin my head? Why does this work?
M.E.Farmer




More information about the Python-list mailing list