在 python 中使用 __next__ 方法的问题
我刚刚开始学习 python,正在阅读有关课程的内容。
这是我为一个简单的可迭代类编写的代码:
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__
方法的示例。甚至这个例子也没有在我的解释器上运行。 感谢您抽出时间来帮助我!
I have just started learning python and am reading about classes .
this is the code i had written for a simple iterable class :
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
for the next() method when i used the __next__
(self):
the following error was displayed
Traceback (most recent call last):
File "class.py", line 20, in <module>
for l in x:
TypeError: instance has no next() method
Can anyone elucidate on this behaviour . i saw an example in the dive into python 3 book by Mark Pilgrim that used the __next__
method . even the example did not run on my interpreter .
Thanks for taking your time off to help me !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的是 Python 2.x,它从那时起就一直使用
.next()
,并且仍然如此 - 只有 Python 3 将该方法重命名为.__next__()
。 Python 2 和 3 不兼容。如果您正在阅读 3.x 书籍,请自己使用 Python 3.x,反之亦然。对于 Python 2.x,您可以将
__next__()
更改为next()
You're using Python 2.x, which has used
.next()
since forever and still does so - only Python 3 renamed that method to.__next__()
. Python 2 and 3 aren't compatible. If you're reading a 3.x book, use Python 3.x yourself, and vice versa.For Python 2.x, you can change
__next__()
tonext()