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?)
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__, theniteris called on the object, and the iterator thatiterreturns does the calling of the underlying object’s__getitem__.)