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
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor