迭代器和可迭代对象
Posted zhoulixiansen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了迭代器和可迭代对象相关的知识,希望对你有一定的参考价值。
from collections.abc import Iterator class Company(object): def __init__(self, employee_list): self.employee = employee_list def __iter__(self): # 一般情况下都是这个样做 return MyIterator(self.employee) # def __getitem__(self, item): # return self.employee[item] class MyIterator(Iterator): def __init__(self, employee_list): self.iter_list = employee_list self.index = 0 def __next__(self): # 真正返回迭代值的逻辑 try: word = self.iter_list[self.index] except IndexError: raise StopIteration # 只有抛出这个异常for循环才能捕获到 self.index += 1 return word if __name__ == "__main__": company = Company(["tom", "bob", "jane"]) my_itor = iter(company) # while True: # try: # print (next(my_itor)) # except StopIteration: # pass # next(my_itor) for item in company: print(item)
为啥不在可迭代对象写迭代器呢?这个是一个编程规范
以上是关于迭代器和可迭代对象的主要内容,如果未能解决你的问题,请参考以下文章