Does Python provide "free" iterators by default?

Possible duplicate:
Why does the definition of getitem in a class make it iterable in python?

I have a class that is basically a wrapper for a python list. In this class, I defined __getitem__ , __setitem__ and __len__ . I have not defined __iter__ for this class.

when i go:

 thing = ListWrapper(range(4)) for i in thing : print i 

I get the output:

 0 1 2 3 

This is good, but I was expecting an error message saying that python could not find an iterator. I looked through the documentation and cannot find anything referring to the default iterators. In addition, tracking the code in PyDev shows that it calls the __getitem__ method for each iteration.

I was wondering how good practice depends on this behavior in my code. This is not quite right at the moment. Does Python provide classes with __getitem__ and __len__ be processed as if they had a specific iterator? Any other oddity information that this may cause is also welcome.

+4
source share
1 answer

If the class does not have __iter__ but has __getitem__ , the iteration engine will call it integer integer integers until it ends.

+3
source

All Articles