problems using __next__ method in python

夙愿已清 提交于 2019-12-04 16:30:45

问题


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 !


回答1:


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__() to next()



来源:https://stackoverflow.com/questions/5982817/problems-using-next-method-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!