在python中,itreable可迭代的——>--iter--。即只要含有--iter--方法的都是可以迭代的
如:
[].__iter__() 迭代器——>__next__。通过next就可以从迭代器中一个一个·的·取值。
只要含有__iter__方法的都是可迭代的——可迭代协议。
迭代器协议
内部含有__iter__和__next__方法的都是迭代器。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from collections import Iterator from collections import Iterable class A: def __iter__(self):pass def __next__(self):pass a = A() print(isinstance(a,Iterator)) print(isinstance(a,Iterable))
当注释掉其中一个时
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from collections import Iterator from collections import Iterable class A: #def __iter__(self):pass def __next__(self):pass a = A() print(isinstance(a,Iterator)) print(isinstance(a,Iterable))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from collections import Iterator from collections import Iterable class A: def __iter__(self):pass #def __next__(self):pass a = A() print(isinstance(a,Iterator)) print(isinstance(a,Iterable))
因此我们可以得知,只要两个方法都存在时才是一个迭代器。
作用
只有是可迭代对象的时候 才能用for循环
当我们遇到一个新的变量时,不确定能不能for循环的时候,可以用来判断它是否可以迭代。
好处
1,从容器类型中一个一个的取值,会把所有的值都取到。
2,它可以节省内存空间。
迭代器并不会在内存中再占有一大块内存,而是随着循环,没错生成一个。即每次next给一个。