【问题标题】:problems using __next__ method in python在 python 中使用 __next__ 方法的问题
【发布时间】:2011-08-24 09:06:15
【问题描述】:

我刚刚开始学习 python 并且正在阅读有关 classes 的内容。

这是我为一个简单的可迭代类编写的代码:

class maths:
          def __init__(self,x):
             self.a=x
          def __iter__(self):
             self.b=0
             return self
          def next(self):
            if self.b <= self.a:
               self.b = self.b+1
               return self.b-1
            else:
               raise StopIteration


x=maths(5)
  for l in x:
       print l

当我使用__next__(self) 时的 next() 方法:
显示以下错误

Traceback (most recent call last):
  File "class.py", line 20, in <module>
    for l in x:
TypeError: instance has no next() method

任何人都可以阐明这种行为。我在 Mark Pilgrim 的 Python 3 书中看到了一个例子,它使用了__next__ 方法。甚至这个例子也没有在我的解释器上运行。 感谢您抽出时间来帮助我!

【问题讨论】:

标签: python-2.6


【解决方案1】:

您正在使用 Python 2.x,它一直使用 .next(),并且仍然如此 - 只有 Python 3 将该方法重命名为 .__next__()。 Python 2 和 3 不兼容。如果您正在阅读 3.x 书籍,请自己使用 Python 3.x,反之亦然。

对于 Python 2.x,您可以将 __next__() 更改为 next()

【讨论】:

  • 将“__next__() 更新为 next()”对我有用,因为我的 IDE PyCharm 版本 2018.3 使用 python 2.7.15。
  • 如果您想确保在您的代码中同时包含 Python2 和 Python3,请在 __next__(self) 函数中编写您的逻辑,并实现一个仅调用 self.__next__()next(self) 方法。这样,当版本切换时,您就会被覆盖
  • 实际上,由于它们是相同的函数,您最好简单地分配它们而不是让一个函数调用另一个函数。 next = __next__ 将使其 2and3 兼容。
猜你喜欢
  • 2018-12-31
  • 2012-09-15
  • 2019-02-02
  • 2020-10-17
  • 2019-05-09
  • 2012-09-04
  • 2022-07-08
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多