1

I am trying to figure out how to make this class work in Python 3, it works in Python 2. This is from a tutorial by D. Beasley for generators. I am new to Python and just working through tutorials online.

Python 2

class countdown(object):
    def __init__(self, start):
        self.count = start
    def __iter__(self):
        return self
    def next(self):
        if self.count <= 0:
            raise StopIteration
        r = self.count
        self.count -= 1
        return r

c = countdown(5)

for i in c:
    print i,

Python 3, not working.

class countdown(object):
    def __init__(self, start):
        self.count = start
    def __iter__(self):
        return self
    def next(self):
        if self.count <= 0:
            raise StopIteration
        r = self.count
        self.count -= 1
        return r

c = countdown(5)

for i in c:
    print(i, end="")
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Neal
  • 104
  • 2
  • 9
  • 1
    This is also covered in the docs https://docs.python.org/3.0/whatsnew/3.0.html#operators-and-special-methods – jonrsharpe Jan 07 '17 at 17:52
  • 1
    Similar [question here](https://stackoverflow.com/questions/7223183/what-are-the-iteration-class-methods-next-and-next-for-and-what-is-the) from 2011. – ILMostro_7 Jan 06 '19 at 09:32

1 Answers1

10

The special method for iterators was renamed from next to __next__ in Python 3 to match other special methods.

You can make it work on both versions without code changes by following the definition of next with:

__next__ = next

so each version of Python finds the name it expects.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks, I was concentrating on __iter__ , as I thought that was the problem, and didn't research the "next" statement. – Neal Jan 07 '17 at 17:57