Python3 实现 可迭代对象和 迭代器对象-新乡seo|网站优化,网站建设_微信公众号:zeropython—昊天博客

[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__

for 循环就是一直调用这个__next__的方法,当遇到StopIteration循环停止.