您的位置:首页 > 编程语言 > Python开发

python 可迭代对象,迭代器,生成器

2018-03-05 11:37 691 查看
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 NotImplemented2.迭代器:
实现了__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.生成器:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python