Answers for "python make class iterable"

1

python make class iterable

"""
Example for a Class that creates an iterator for each word in a sentence

The keyword 'yield' is key (no pun intended) to the solution. It works the
same as return with the exception that on the next call to the function it
will resume where it left off
"""

class Counter:
    def __init__(self, low, high):
        self.current = low - 1
        self.high = high

    def __iter__(self):
        return self

    def __next__(self): # Python 2: def next(self)
        self.current += 1
        if self.current < self.high:
            return self.current
        raise StopIteration


for c in Counter(3, 9):
    print(c)
Posted by: Guest on June-02-2021

Python Answers by Framework

Browse Popular Code Answers by Language