0

I am trying to learn how iterators, generators and decorators works in python based on the tutorials in this website.

In the first example, he/she demonstrate a simple example as below:

class Count:
    def __init__(self, low, high):
        self.low = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current +=1
            return self.current -1

The problem is, I can't iterate over objects of this class:

>>> ================================ RESTART ================================
>>> 
>>> c = Count(1, 10)
>>> for i in c:
    print i



Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    for i in c:
TypeError: instance has no next() method
>>> 

What's wrong?

1 Answer 1

4

That tutorial appears to be for Python 3.

In Python 2 iterators must have the next() method (PEP 3114 - Renaming iterator.next() to iterator.__next__()):

class Count:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current +=1
            return self.current -1
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. Anyway, why I don't receive Undefined Variable error for self.current? what is its value when the line self.current +=1 run for first time?
@Abraham I think it should be self.current = low
@Abraham: You will indeed get an error. You should initialize self.current in __init__.
@Abraham - what do you get if you print self.current as the first statement of next()?
An alternative solution to renaming __next__ to next in your function would be to switch Python interpreters so that you're using Python 3 like your tutorial expects. Many aspects of Python 3 are better than Python 2, most notably its handling of Unicode text. There are some modules that are only available for Python 2, but that number is diminishing steadily, so unless you're sure you need one of them already, I'd suggest learning Python 3 first, rather than learning Python 2 and then learning how to port your code to Python 3 later on.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.