What is the interface for python iterators? [duplicate]

牧云@^-^@ 提交于 2020-01-14 09:38:06

问题


Possible Duplicate:
Build a Basic Python Iterator

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 facto 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

回答1:


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.

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




回答2:


According to the glossary, an iterator is any object with a next() method, and a __iter__() method.




回答3:


Section 4.5 - Iterator Types

You need to define for your container:

container.__iter__() #-> returns iterator

and for your iterator your must define:

iterator.__iter__() #-> returns self
iterator.__next__() #-> returns next item
iterator.next() #(for Python2 compatibility) -> returns self.__next__()


来源:https://stackoverflow.com/questions/13094421/what-is-the-interface-for-python-iterators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!