[Tutor] making object iterable
Siim Märtmaa
foobar8 at gmail.com
Sat Feb 5 22:39:37 CET 2011
2011/2/5 Alex Hall <mehgcap at gmail.com>:
> Yes, I get the same thing. However, when you try to index, as in a[0],
> you have problems. Here are two lines from my program:
> for i in res: print i
> This works as expected, printing every object in res.results, just as I wanted.
>
> for i in range(len(res)): print str(i+1)+": "+str(res[i])
> This gives me an error, on this line, that "TypeError: 'SearchResults'
> object does not support indexing". So it seems that I can iterate over
> the list, but not get at a given element. What builtin method do I
> need to overload to do this?
It is the __getitem__ method
Strange that when I ran code that I wrote to look like yours, I got a
different error:
AttributeError: itertest instance has no attribute '__getitem__'
My code:
####
class itertest():
testlist = [1,2,32,4,5,6,7,8]
def __iter__(self):
return iter(self.testlist)
def __len__(self):
return len(self.testlist)
def __getitem__(self, i):
return self.testlist[i]
tester = itertest()
for i in range(len(tester)): print str(i+1)+": "+str(tester[i])
####
I think in this case it would be more readable to use enumerate
instead of range(len(sequence))
for index, item in enumerate(tester): print str(index+1)+": "+str(item)
or in some cases string substitution
for index, item in enumerate(tester): print "%d: %s"%(index+1,item)
More information about the Tutor
mailing list