问题
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