如何使对象成为Python2和Python3迭代器? [英] How to make an object both a Python2 and Python3 iterator?

查看:195
本文介绍了如何使对象成为Python2和Python3迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此Stack Overflow帖子是关于使对象成为Python中的迭代器。 / p>

在Python 2中,这意味着您需要实现 __ iter __()方法和 next()方法。但是在Python 3中,你需要实现一个不同的方法,而不是 next()你需要实现 __ next __( )



如何在Python 2和3中创建一个迭代器对象?

解决方案

只需给它 __ next __ next 方法;一个可以是另一个的别名:

  class Iterator(object):
def __iter __(self):
返回self

def __next __(self):
#Python 3
返回'a value'

next = __next__#Python 2


This Stack Overflow post is about making an object an iterator in Python.

In Python 2, that means you need to implement an __iter__() method, and a next() method. But in Python 3, you need to implement a different method, instead of next() you need to implement __next__().

How does one make an object which is an iterator in both Python 2 and 3?

解决方案

Just give it both __next__ and next method; one can be an alias of the other:

class Iterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        # Python 3
        return 'a value'

    next = __next__  # Python 2

这篇关于如何使对象成为Python2和Python3迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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