一个对象若要用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 if __name__=='__main__': stus=Student(['aa','bb','cc','ee']) for stu in stus: print(stu) print(isinstance(stus,Iterable)) print(isinstance(stus, Iterator)) print(next(stus))
标签:__,迭代,python,self,生成器,iter,studentList,def From: https://www.cnblogs.com/howhy/p/17877692.html