首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

创设自己的迭代器

2012-12-22 
创建自己的迭代器# -*- coding: utf-8 -*-创建自己的迭代器类,需要实现两个方法:1. __iter__: The iter

创建自己的迭代器

# -*- coding: utf-8 -*-'''创建自己的迭代器类,需要实现两个方法:1. __iter__: The iter method simply returns a reference to the object itself and is always implemented to do so.2. __next__: '''class _BagIterator:        def __init__(self, theList):        self._bagItems = theList        self._curItem = 0    def __iter__(self):        return self    def __next__(self):        if self._curItem < len(self._bagItems):            item = self._bagItems[self._curItem]            self._curItem += 1            return item        else:            raise StopIteration

热点排行