码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器和可迭代对象

时间:2018-12-06 21:24:01      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:编程规范   name   for   self   编程   __name__   迭代   ret   from   

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)

为啥不在可迭代对象写迭代器呢?这个是一个编程规范

迭代器和可迭代对象

标签:编程规范   name   for   self   编程   __name__   迭代   ret   from   

原文地址:https://www.cnblogs.com/zhoulixiansen/p/10079536.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!