17

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 !

David Zheng
  • 797
  • 7
  • 21
Draklor40
  • 171
  • 1
  • 1
  • 3
  • Related: [there's no next() function in a yield generator in python 3](https://stackoverflow.com/questions/12274606/theres-no-next-function-in-a-yield-generator-in-python-3) – user2314737 Jun 17 '17 at 21:59

1 Answers1

49

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

  • Updating "__next__() to next()" worked for me as my IDE PyCharm version 2018.3 uses python 2.7.15. – Hardian Feb 06 '19 at 20:58
  • If you want to make sure to have both Python2 and Python3 covered in your code, write your logic in the `__next__(self)` function, and implement a `next(self)` method that only calls `self.__next__()`. That way you're covered if and when the version is switched – enrm Aug 13 '19 at 07:39
  • Actually since they are the same function you're better off simply assigning them rather than making one function call the other. ``next = __next__`` will cause it be 2and3 compatible. – Tatarize Nov 05 '19 at 17:44