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

一个对象若要用for 循环 则需实现def __iter__(self, item) 或def __iter__(self, item)方法

可迭代对象 实现了def __iter__(self, item)方法  

迭代器  实现了def __iter__(self, item)和def __next__(self)方法  

迭代器一定是可迭代对象 可迭代对象不一定是迭代器

生成器是一个特殊的迭代器

 

from collections.abc import Iterable,Iterator
class Student():
def __init__(self,studentList):
self.studentList=studentList
self._index=0
def __getitem__(self, item):
return self.studentList[item]
def __iter__(self):
return iter(self.studentList)
def __next__(self):
stu=self.studentList[self._index]
self._index+=1
return stu

def genfun():
print('hello')
yield 6
print('end')

if __name__=='__main__':

stus=Student(['aa','bb','cc','ee'])
for stu in stus:
print(stu)
for stu in stus:
print(stu)
print(isinstance(stus,Iterable))
print(isinstance(stus, Iterator))
print(next(stus))
t=genfun()
print(next(t))
next(t)
posted @ 2023-12-05 17:06  howhy  阅读(3)  评论(0编辑  收藏  举报