我刚刚开始学习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
Run Code Online (Sandbox Code Playgroud)
对于next()方法,当我使用__next__(self)时:
显示以下错误
Traceback (most recent call last):
File "class.py", line 20, in <module>
for l in x:
TypeError: instance has no next() method
Run Code Online (Sandbox Code Playgroud)
任何人都可以阐明这种行为.我看到了Mark Pilgrim使用这种__next__方法进入python 3书的一个例子.即使这个例子没有在我的翻译上运行.谢谢你抽出时间来帮助我!
python-2.6 ×1