problems using __next__ method in python

Draklor40 picture Draklor40 · May 12, 2011 · Viewed 13.2k times · Source

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 !

Answer

user395760 picture user395760 · May 12, 2011

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()