I'm new to Python and I'm reading the book Python Tricks. In the chapter about generators, it gives the following example (with some changes)
class BoundedGenerator:
def __init__(self, value, max_times):
self.value = value
self.max_times = max_times
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count < self.max_times:
self.count += 1
yield self.value
After that, I write a loop, instantiate the generator and print the value:
for x in BoundedGenerator('Hello world', 4):
print(next(x))
Why do I have to call the next(X)
inside the loop?
I (think) I understand that the __iter__
function will be called in the loop line definition and the __next__
will be called in each iteration, but I don't understand why I have to call the next again inside the loop. Is this not redundant?
If I don't call the __next__
function, my loop will run forever.