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.生成器:
实现了__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 可迭代的对象、迭代器和生成器
- 第八章 Python可迭代对象、迭代器和生成器
- Python 可迭代的对象、迭代器和生成器
- Python3.可迭代对象_迭代器_生成器
- 【python】14、完全理解可迭代对象、迭代器、生成器
- Python迭代对象、迭代器、生成器
- Python迭代器,可迭代对象,生成器
- python之迭代器、生成器、可迭代对象
- 完全理解 Python 迭代对象、迭代器、生成器
- python迭代,可迭代对象,生成器,迭代器--
- python中生成器和迭代器以及可迭代对象的区别
- 完全理 4000 解 Python 迭代对象、迭代器、生成器
- Python之列表生成式、生成器、可迭代对象与迭代器
- 完全理解 Python 迭代对象、迭代器、生成器
- 完全理解Python迭代对象、迭代器、生成器
- 完全理解 Python 迭代对象、迭代器、生成器
- 完全理解Python迭代对象、迭代器、生成器
- Python 可迭代的对象、迭代器和生成器
- 完全理解 Python 迭代对象、迭代器、生成器
- 理解Python迭代对象、迭代器、生成器