So I understand that sometimes instead of defining iter and next methods within a class that is supposed to be iterable, using just an iter method containing a yield statement suffices. Actually why? Just do avoid boilerplate code?
However, I dont get why the following snippet yields three iterations
class BoundedRepeater:
def __init__(self, value, max_repeats):
self.value = value
self.max_repeats = max_repeats
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count >= self.max_repeats:
raise StopIteration
self.count += 1
return self.value
if called like this
for item in BoundedRepeater("Hello", 3):
print(item)
but if I change the methods to
class BoundedRepeater: def init(self, value, max_repeats): self.value = value self.max_repeats = max_repeats self.count = 0
class BoundedRepeater:
def __init__(self, value, max_repeats):
self.value = value
self.max_repeats = max_repeats
self.count = 0
def __iter__(self):
if self.count >= self.max_repeats:
raise StopIteration
self.count += 1
yield self.value
I only get one iteration instead of three