【问题标题】:python 2 vs python 3 class with __iter__ [duplicate]带有__iter__的python 2 vs python 3类[重复]
【发布时间】:2017-05-22 07:51:56
【问题描述】:

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

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,

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="")

【问题讨论】:

标签: python python-2.7 python-3.x iterator


【解决方案1】:

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

按照next 的定义,您可以在不更改代码的情况下使其在两个版本上工作:

__next__ = next

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

【讨论】:

  • 谢谢,我专注于 iter ,因为我认为这是问题所在,因此没有研究“下一个”语句。
猜你喜欢
  • 2018-04-19
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多