from collections import Iterable,Iterator from abc import ABCMeta, abstractmethod assert 1 in [1,2,3] # assert 4 in [1,2,3] # assert len([1,2]) >=5,‘列表元素个数小于5‘ d = {1: ‘foo‘, 2: ‘bar‘, 3: ‘qux‘} assert 1 in d # assert ‘foo‘ in d print(isinstance(iter([]),Iterable))#True print(isinstance(iter([]),Iterator))#True print(isinstance([],Iterable))#True for i in iter([1,2,3]): print(‘111‘,i,type(i),type(iter([1,2,3]))) ‘‘‘ 111 1 <class ‘int‘> <class ‘list_iterator‘> 111 2 <class ‘int‘> <class ‘list_iterator‘> 111 3 <class ‘int‘> <class ‘list_iterator‘> ‘‘‘ class Fib: def __init__(self): self.prev = 0 self.curr = 1 def __iter__(self): return self def __next__(self): value = self.curr self.curr += self.prev self.prev = value return value f = Fib() print(isinstance(f,Iterable))#True print(isinstance(f,Iterator))#True
结论:
可迭代对象:可以进行for循环都是可迭代对象,原因是其内部实现了一个__iter__方法
迭代器:能够进行next(迭代器对象),都是迭代器对象,其内部实现了__iter__和__next__方法
生成器:元祖推导式和函数里使用yield的函数都是生成器
生成器属于迭代器
迭代器属于可迭代对象
原文地址:https://www.cnblogs.com/ldq1996/p/8485440.html
时间: 2024-10-16 06:41:58