开发者

problems using __next__ method in python

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开发者_Go百科 taking your time off to help me !


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜