So this is my code:
class Test:
def __init__(self, lst):
self.lst = lst
def generator(self, func):
for i in self.lst:
yield func(str(i))
a = Test(['hello', 'world'])
print(next(a.generator(str.upper)))
print(next(a.generator(str.upper)))
I'm new to generators and can't see what im doing wrong. I want to pass in a function, in this case the upper() function and yield the result.
The output I get: 'HELLO' 'HELLO'
The output i want: 'HELLO' 'WORLD'
CodePudding user response:
Every time you call a function that uses the yield
keyword, you get a different generator object. If you want to use the same one, then you need to call the function once and store the result in a variable.
my_generator = a.generator(str.upper)
print(next(my_generator))
print(next(my_generator))
CodePudding user response:
You reconstructed the generator, meaning you started again at the first value. What you want to do is instantiate the generator once, and pass the same reference to next
multiple times:
test = Test(['hello', 'world'])
gen = test.generator(str.upper))
print(next(gen))
print(next(gen))