python迭代器的接口是什么? [英] What is the interface for python iterators?

查看:160
本文介绍了python迭代器的接口是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

构建一个基本的Python迭代器

有哪些必要的方法用于定义迭代器?例如,在下面的Infinity迭代器中,它的方法是否足够?是否有其他标准或de因子标准方法定义迭代器?

What are the required methods for defining an iterator? For instance, on the following Infinity iterator, are its methods sufficient? Are there other standard or de factor standard methods that define an iterator?

class Infinity(object):
    def __init__(self):
        self.current = 0

    def __iter__(self):
        return self

    def next(self):
        self.current += 1
        return self.current


推荐答案

你拥有的东西足以支持Python 2.x,但是在Python 3.x中你需要定义函数 __ next __ 而不是 next ,请参阅 PEP 3114

What you have is sufficient for Python 2.x, but in Python 3.x you need to define the function __next__ instead of next, see PEP 3114.

如果您需要与2.x和3.x兼容的代码,请同时包含这两个代码。

If you need code that is compatible with both 2.x and 3.x, include both.

这篇关于python迭代器的接口是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆