[Tutor] making object iterable
Alex Hall
mehgcap at gmail.com
Sat Feb 5 23:08:54 CET 2011
On 2/5/11, Siim Märtmaa <foobar8 at gmail.com> wrote:
> 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
Thanks, that did it.
>
> 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])
>
> ####
Not sure. Is it because you did not declare it as an object class:
class myClass(object): ...
>
> 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)
Very true, I always forget about that handy function.
>
> or in some cases string substitution
>
> for index, item in enumerate(tester): print "%d: %s"%(index+1,item)
Also true, and something I really should do more. I have heard it is
faster than concatenating anyway.
>
--
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap
More information about the Tutor
mailing list