Python for循环与getitem的关系详解

```In [169]: class Foo:
...:   def __getitem__(self, pos):
...:     print(pos)
...:     return range(10)[pos]
...:  ```
```In [172]: for i in f:
...:   ...
...:
...:
0
1
2
3
4
5
6
7
8
9
10```

```In [173]: class Foo:
...:   def __getitem__(self, pos):
...:     if pos >5:
...:       raise StopIteration
...:     print(pos)
...:     return range(10)[pos]
...: ```
```In [177]: for i in f:
...:   ...
...:
0
1
2
3
4
5```

```   ...:   def __getitem__(self, pos):
...:     if pos >5:
...:       raise IndexError
...:     print(pos)
...:     return range(10)[pos]
...:

In [182]:

In [182]: f = Foo()

In [183]: for i in f:
...:   ...
...:
0
1
2
3
4
5```

```In [184]: list(f)
0
1
2
3
4
5
Out[184]: [0, 1, 2, 3, 4, 5]```

```In [185]: from collections import Iterable
In [186]: isinstance(f, Iterable)
Out[186]: False

In [187]: iter(f)
Out[187]: <iterator at 0x114f2be50>```
```dir(f)
Out[189]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__']```