I am learning about self-defined iterator, and confused with the example from below. My learning understanding with __iter__
, __next__
so far is:
__iter__
generates a iterator, and __next__
goes through this iterator object for its contained values one by one (to me, this means __next__
needs an iterator object to work with. However, in the following code.
The CirleIterator()
class does not have __iter__(self)
, to me this means this class does not create a iterator, then what the __next__()
is doing here by itself? There is no iterator object for __next__()
to use here.
The Cirle()
class has the __iter__
step which return the object from the CircleIterator()
class. My understanding from reading is __iter__
needs to return an iterator, but we just said the CircleIterator()
class did not generate a iterator. So why do we even put it here?
I also tried to run the CircleIterator()
class alone. And tried out things like CircleIterator('abc', 3).__next__()
. This returns me nothing.
class CircleIterator():
def __init__(self, data, max_times):
self.data = data
self.max_times = max_times
self.index = 0
def __next__(self):
if self.index >= self.max_times:
raise StopIteration
value = self.data[self.index % len(self.data)]
self.index += 1
return value
class Circle():
def __init__(self, data, max_times):
self.data = data
self.max_times = max_times
def __iter__(self):
return CircleIterator(self.data, self.max_times)
c = Circle('abc', 5)
print(list(c))