开发者

Does Python provide "free" default iterators? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

I have a class that is basically a wrapper for a python list. Within this class I have 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

Which is nice, but I expected an error message of some sort saying tha开发者_如何学Pythont python could not find an iterator. I've given the documentation a look and can't find anything referencing default iterators. Furthermore, tracing through the code in PyDev shows that it is calling the __getitem__ method each iteration.

I was wondering if it is good practice to depend on this behavior in my code. It doesn't fell quite right to me at this point. Does Python guarantee that classes with __getitem__ and __len__ will be treated as if they have a defined iterator? Any other information on weirdness this may cause is also welcome.


If a class doesn't have __iter__, but does have __getitem__, the iteration machinery will call it with consecutive integers until it runs out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜