
Code
Build Your Own Iterator
Any object can join the iteration protocol by defining two dunder methods:
__iter__(self)returns the iterator. For an iterator, that's justself.__next__(self)returns the next value, or raisesStopIterationwhen done.
class Doubling:
def __init__(self, limit):
self.value = 1
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.value > self.limit:
raise StopIteration
current = self.value
self.value *= 2
return current
print(list(Doubling(20))) # [1, 2, 4, 8, 16]
That's it! Now for, list(), sum(), zip() and friends all work with it.
One rule to remember: once __next__ raises StopIteration, it should keep
raising it on every later call. Iterators don't restart.
Assignment
Write a class Countdown:
Countdown(start)stores where to start.- Iterating over it gives
start, start - 1, ..., 1, then stops.list(Countdown(3))is[3, 2, 1]. Countdown(0)(or any number below 1) gives nothing at all.__iter__returnsself.- When it is finished, every later
next()raisesStopIterationagain.
Write a class Countdown:
Countdown(start)stores where to start.- Iterating over it gives
start, start - 1, ..., 1, then stops.list(Countdown(3))is[3, 2, 1]. Countdown(0)(or any number below 1) gives nothing at all.__iter__returnsself.- When it is finished, every later
next()raisesStopIterationagain.
main.py Python sleeping
Press Run to try your code, then Check to test it.