py> from __future__ import generators Hello again, 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): ... 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> r = R3('qwerty') py> r.__class__ <class __main__.R3 at 0x01440A38> py> r.__iter__ <bound method R3.__iter__ of <__main__.R3 instance at 0x0141BFB0>> py> r.__iter__() <stackless.generator object at 0x0143FE38> py> a = r.__iter__() py> a.next() 'y'
py> a.next() 't' py> a.next() 'r' py> a.next() 'e' py> a.next() 'w' py> a.next() 'q' py> a.next() Traceback (most recent call last): File "<input>", line 1, in ? StopIteration >>> 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. M.E.Farmer Deeper down the rabbit hole. M.E.Farmer wrote: > 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 -- http://mail.python.org/mailman/listinfo/python-list