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?)

Community
  • 1
  • 1
harish
  • 109
  • 2
  • 6

1 Answers1

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__.)

ben w
  • 2,490
  • 14
  • 19