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)

猜你喜欢

转载自www.cnblogs.com/callyblog/p/11080021.html
今日推荐