[code lnag="python"]
In [1]: l = [1,2,3]
In [2]: s = 'abcdef'
In [3]: for x in l:print(x)
1
2
3
In [4]: for x in s:print(x)
a
b
c
d
e
f
# 能for 循环输出 说明是可迭代对象
In [5]: iter?
Docstring:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
Type: builtin_function_or_method
# iter 可以从可迭代对象 --> 迭代器对象
In [6]: iter(l)
Out[6]: <list_iterator at 0x111aa44e0>
In [11]: l.__iter__() #等价于 iter(l)
Out[11]: <list_iterator at 0x111ad9940>
In [7]: iter(s)
Out[7]: <str_iterator at 0x111aae358>
In [12]: s.__iter__() # 等价于 iter(s)
Out[12]: <str_iterator at 0x111b084a8>
总结: iter先去找 __iter__ 如果没有就去找 __getitem__
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
In
[
16
]
:
ll
=
iter
(
l
)
In
[
17
]
:
ll
Out
[
17
]
:
<
list_iterator
at
0x111b508d0
>
In
[
19
]
:
ll
.
__next__
(
)
Out
[
19
]
:
1
In
[
20
]
:
ll
.
__next__
(
)
Out
[
20
]
:
2
In
[
21
]
:
ll
.
__next__
(
)
Out
[
21
]
:
3
In
[
22
]
:
ll
.
__next__
(
)
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
StopIteration
Traceback
(
most
recent
call
last
)
<
ipython
-
input
-
22
-
1d8aafd9727f
>
in
<
module
>
(
)
--
--
>
1
ll
.
__next__
(
)
StopIteration
:
|
for 循环就是一直调用这个__next__的方法,当遇到StopIteration循环停止.