代码:
>>> from collections import Iterator,Iterable
>>>
>>>
>>> from collections import Iterator,Iterable
>>> l = [1,2,3,4,5]
>>> for x in l:
... print(x)
...
1
2
3
4
5
>>> isinstance(l,Iterable)
True
>>> issubclass(list,Iterable) # 判断List是否是iterable的子类
True
>>> issubclass(str,Iterable)
True
>>> issubclass(dict,Iterable)
True
>>> issubclass(int,Iterable)
False
>>> iter(l) # 由可迭代对象生成一个迭代器对象
<list_iterator at 0x7f7947313d68>
>>> l.__iter__() # iter实际调用的是__iter__()方法
<list_iterator at 0x7f7946d8e668>
>>> Iterable.__abstractmethods__ # 实际调用的是抽象基类的抽象方法
frozenset({'__iter__'})
>>> it = iter(l)
>>> next(it) # 迭代器对象的next方法
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-131-bc1ab118995a> in <module>
----> 1 next(it)
StopIteration:
>>> it.__next__() # 实际调用的是迭代器对象的__next__()方法
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-132-74e64ed6c80d> in <module>
----> 1 it.__next__()
StopIteration:
>>> it = iter(l)
>>> next(it)
1
>>> next(it)
2
>>> list(it) # 迭代器对象是一次性消费的
[3, 4, 5]
>>> list(it)
[]
>>> it = iter(l)
>>> list(it)
[1, 2, 3, 4, 5]
>>> it = iter(l)
>>> it2 = iter(l)
>>> next(it)
1
>>> next(it)
2
>>> next(it2) # 两个迭代器对象消费各不干扰
1
>>> it = iter(l)
>>> for x in it: # 迭代器本身也是可以迭代的,它也是可迭代对象
... print(x)
...
1
2
3
4
5
>>> isinstance(it,Iterable)
True
>>> isinstance(it,Iterator)
True
>>> it.__iter__()
<list_iterator at 0x7f7946deb2e8>
>>> it.__iter__() is it # 迭代器对象的__iter__()方法返回的是自身
True
>>>