Python中的可迭代对象和迭代器对象

Python中的可迭代对象和迭代器对象是两种不同的东西,可迭代对象是Iterable,迭代器对象是Iterator

>>> from collections import Iterator
>>> from collections import Iterable
>>> l = [1, 2, 3]
>>> s = 'abc'
>>> isinstance(l, Iterable)
True
>>> isinstance(s, Iterable)
True
>>> isinstance(l, Iterator)
False
>>> isinstance(s, Iterator)
False

查看list类和str类,里面有一个_iter_方法

>>> l_i = l.__iter__()
>>> s_i = s.__iter__()
>>> isinstance(l_i, Iterator)
True
>>> isinstance(s_i, Iterator)
True

通过_iter_产生的对象进行next

>>> next(l_i)
1
>>> next(l_i)
2
>>> next(l_i)
3
>>> next(l_i)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

这与用for进行迭代比较发现结果相同,所以for的内部执行逻辑就是先调用对象的_iter_方法,然后一直进行next直到抛出StopIteration

你可能感兴趣的:(Python中的可迭代对象和迭代器对象)