Python Forum

Full Version: Please, how do I call the method inside this class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I understand about methods and variables in classes but I was reading this book on data structures and understand what the author was saying until he wrote a utility function inside a class, a progression class. The class is an iterator that implements the __next__ special method. The class on the other hand has a utility method, print_progression, that calls the special method to print the next n numbers. I have been trying to call the utility function to print out the values in the __next__ special method but I have been unsuccessful. Can anyone show me how to do so and what concepts are involved? Thanks.
class Progression :
    def __init__(self, start=0):
        self._current = start

    def _advance(self):
        self._current += 1

    def __next__(self):
        if self._current is None :
            raise StopIteration()
        else :
            answer = self._current
            self._advance()
            return answer

    def print_progression(self, n):
        print(''.join(str(next(self) for j in range(n))))
What I have done so far and did not success.
I tried:
if __name__ == '__main__' :
    genericProg = Progression(1)
    genericProg.print_progression(5)
The output is:
Output:
<generator object Progression.print_progression,<locals>.<genexpr> at xxxxx>
Please, what am I doing wrong and how do I call that method. Someone help me please. The interpreter is saying this is a generator object but the method has no yield statement. I am totally confused about this.
You have
print(''.join(str(next(self) for j in range(n))))
which is turning a generator into a string str(next(self) for j in range(n))
i think what you are looking for is
print(''.join(str(next(self)) for j in range(n)))
which is turning the next item into a string str(next(self))

The following
print(type(i for i in range(2)))
creates a generator
Output:
<class 'generator'>
whereas including square brackets
print(type([i for i in range(2)]))
creates a list
Output:
<class 'list'>