python 2 vs python 3 类与 __iter__

Nea*_*al 1 python iterator python-2.7 python-3.x

我试图弄清楚如何让这个类在 Python 3 中工作,它在 Python 2 中工作。这是来自 D. Beasley 的生成器教程。我是 Python 新手,只是在网上学习教程。

蟒蛇 2

class countdown(object):
    def __init__(self, start):
        self.count = start
    def __iter__(self):
        return self
    def next(self):
        if self.count <= 0:
            raise StopIteration
        r = self.count
        self.count -= 1
        return r

c = countdown(5)

for i in c:
    print i,
Run Code Online (Sandbox Code Playgroud)

Python 3,不工作。

class countdown(object):
    def __init__(self, start):
        self.count = start
    def __iter__(self):
        return self
    def next(self):
        if self.count <= 0:
            raise StopIteration
        r = self.count
        self.count -= 1
        return r

c = countdown(5)

for i in c:
    print(i, end="")
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 9

迭代器的特殊方法在 Python 3 中从nextto重命名__next__以匹配其他特殊方法。

您可以按照nextwith的定义使其在两个版本上都正常工作,而无需更改代码:

__next__ = next
Run Code Online (Sandbox Code Playgroud)

所以每个版本的 Python 都会找到它期望的名称。