我刚刚开始学习 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__
时的 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 的《dive into python 3》一书中看到了一个使用
__next__
的例子。方法 。甚至这个例子也没有在我的解释器上运行。感谢您抽出时间来帮助我!
最佳答案
您正在使用 Python 2.x,它使用了 .next()
因为永远并且仍然如此 - 只有 Python 3 将该方法重命名为 .__next__()
. Python 2 和 3 不兼容。如果您正在阅读 3.x 书籍,请自己使用 Python 3.x,反之亦然。
对于 Python 2.x,您可以更改 __next__()
至 next()
关于python-2.6 - 在python中使用__next__方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5982817/