Jun-26-2020, 12:58 PM
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.
What I have done so far and did not success.
I tried:
The output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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)))) |
I tried:
1 2 3 |
if __name__ = = '__main__' : genericProg = Progression( 1 ) genericProg.print_progression( 5 ) |
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.