[Tutor] special attributes naming confusion

Emile van Sebille emile at fenx.com
Thu Jun 7 18:11:26 CEST 2012


On 6/6/2012 4:28 PM Steven D'Aprano said...
> Prasad, Ramit wrote:
>>> That is, for loops first try to build an iterator by calling
>>> __iter__, and if
>>> that fails they try the sequence protocol obj[0], obj[1], obj[2], ...
>>
>> So...I could instead write __getitem__ for the same effect?
>
>
> Er, no... __getitem__ and __iter__ do very different things. __getitem__
> returns individual items, and __iter__ returns an iterator object which,
> when passed to the next() builtin, returns the next item.

I'd say it depends on what you need when you say for the same effect.

This is the same effect for some definition thereof:

class Iterable:
     def __init__(self,count):
         self.maxitems=count
     def result(self,idx):
         return idx**idx
     def __getitem__(self,idx):
         if idx<self.maxitems:
             return self.result(idx)
         else:
             raise IndexError


for ii in Iterable(5):
     print ii


Emile




More information about the Tutor mailing list