我是靠谱客的博主 自由香烟,这篇文章主要介绍python 枚举器和生成器 __iter__ 魔法方法和 yield,现在分享给大家,希望可以做个参考。

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

python的枚举器类需要实现__iter__魔法方法返回枚举器实例,还需要实现一个next方法,在枚举到末尾时抛出StopIteration异常表示枚举结束。如下简单示例:

class SimpleIterator:
    def __init__(self,maxvalue):
        self.current = 0
        self.max = maxvalue

    def next(self):
        result = self.current
        self.current += 1
        if result == self.max : raise StopIteration()
        return result

    def __iter__(self):
        return self

li = list(SimpleIterator(5))
print li

yield生成器实现示例如下:

def yield_test(maxvalue):
    i = -1
    while i < maxvalue-1:
        i += 1
        yield i

for i in yield_test(10):
    print i

转载于:https://my.oschina.net/u/89296/blog/48518

最后

以上就是自由香烟最近收集整理的关于python 枚举器和生成器 __iter__ 魔法方法和 yield的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(99)

评论列表共有 0 条评论

立即
投稿
返回
顶部