python 自定义Iterator对象

from collections.abc import Iterator

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __iter__(self):
        return MyIterator(self.employee) # 将list传入到这个里面自定义的Iterator里面,并且实现了__iter__,那么这个对象就可以是Iterator对象

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 # 这里必须抛出StopIteration,不然会一直跑
        self.index += 1
        return word

if __name__ == "__main__":
    company = Company(["tom", "bob", "jane"])

    for item in company:
        print (item)

 

posted @ 2019-06-24 22:46  下路派出所  阅读(480)  评论(0编辑  收藏  举报