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

编写一个生成器需要编写__iter__和__next__

时间:2018-06-29 11:14:17      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:return   for   编写   __next__   item   raise   ext   +=   ati   

 

class _Iterator:
    """ 迭代器类 """
    def __init__(self,seq=None):
        self._bag_items = [1,2,3,4,5] if seq is None else seq
        self._cur_item = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._cur_item < len(self._bag_items):
            item = self._bag_items[self._cur_item]
            self._cur_item += 1
            return item
        else:
            raise StopIteration

__next__ for循环每次迭代会调用

__iter_返回本身就行, 本身就是迭代器

编写一个生成器需要编写__iter__和__next__

标签:return   for   编写   __next__   item   raise   ext   +=   ati   

原文地址:https://www.cnblogs.com/chaiming/p/9241527.html

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