Python2与Python3类的比较__

2024-10-02 00:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何使这个类在Python3中工作,它在Python2中工作。这是D.Beasley的发电机教程。我是Python的新手,正在学习在线教程。在

Python2

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,

Python3,不工作。在

^{pr2}$

Tags: selfreturnobjectinitdefcount教程start
1条回答
网友
1楼 · 发布于 2024-10-02 00:26:30

在python3中,迭代器的特殊方法从next重命名为__next__,以匹配其他特殊方法。在

通过遵循next的定义,您可以使它在两个版本上都工作,而无需更改代码:

__next__ = next

因此,Python的每个版本都会找到它期望的名称。在

相关问题 更多 >

    热门问题