Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Please, how do I call the method inside this class
#1
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.
Quote
#2
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'>
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  class method on two object gabejohnsonny21 4 217 Apr-22-2020, 06:57 AM
Last Post: DeaD_EyE
  Class/Method Confusion ramadan125 1 874 Sep-10-2018, 12:19 AM
Last Post: ichabod801
  call an instance of a class in the interactive nzcan 3 962 Aug-23-2018, 10:47 AM
Last Post: nzcan
  Class and calling a method Zatoichi 3 1,146 Mar-13-2018, 08:44 PM
Last Post: Zatoichi
  List not passing between methods inside a class definition ijosefson 5 1,996 Oct-15-2017, 07:15 PM
Last Post: ijosefson

Forum Jump:


Users browsing this thread: 1 Guest(s)