1.可迭代对象:
实现了__iter__()方法的对象就是一个可迭代对象。
验证一个对象是否是可迭代对象的方法:
from collections import Iterable
from collections import Iterator
a=[1,2,3,4,5]
isinstance(a,Iterable)
True #是可迭代对象
isinstance(a,Iterator)
False #不是迭代器
如下是Iterable的源码:
class Iterable(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
2.迭代器:
实现了__iter__()方法和__next()__方法的对象就是一个可迭代对象。
看collections中Iterator的源码:
class Iterator(Iterable): #继承Iterable
__slots__ = ()
@abstractmethod
def __next__(self): #多了一个__next__()
'Return the next item from the iterator. When exhausted, raise StopIteration'
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if (any("__next__" in B.__dict__ for B in C.__mro__) and
any("__iter__" in B.__dict__ for B in C.__mro__)):
return True
return NotImplemented
3.生成器: