Python Forum
Please, how do I call the method inside this class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Please, how do I call the method inside this class (/thread-27902.html)



Please, how do I call the method inside this class - Emekadavid - Jun-26-2020

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.


RE: Please, how do I call the method inside this class - Yoriz - Jun-26-2020

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'>