1

Possible Duplicate:
Why does defining getitem on a class make it iterable in python?

class b: def __getitem__(self, k): return k cb = b() for k in cb: print k 

I get the output:

0 1 2 3 4 5 6 7 8 ..... 

Iterating over instance of class b, emits integers. Why is that?

(came across the above program when looking at Why does defining __getitem__ on a class make it iterable in python?)

3
  • 1
    Why did you post an exact duplicate of a question you linked to and was already perfectly answered there? Commented Feb 4, 2012 at 22:47
  • @Rob In that post, i had some trouble figuring out as to why integers were being output Commented Feb 4, 2012 at 22:58
  • In hindsight, i should have looked at semantics of getitem before posting this question Commented Feb 4, 2012 at 23:05

1 Answer 1

3

Because the for-loop is implemented for objects that define __getitem__ but not __iter__ by passing successive indices to the object's __getitem__ method. See the effbot. (What really happens under the covers IIUC is a bit more complicated: if the object doesn't provide __iter__, then iter is called on the object, and the iterator that iter returns does the calling of the underlying object's __getitem__.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.