Python Interlator Questions

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

class MultipleIterator:
    def __init__(self, stop, divisor):
        self.current = 0
        self.stop = stop
        self.divisor = divisor

    def __iter__(self):
        return self

    def __next__(self):
        self.current += 1
        if self.current < self.stop:
            if self.current % self.divisor == 0:
                return self.current
            raise StopIteration

for i in MultipleIterator(20, 3):
    print(i, end=' ')

# Execution result
None None 3 None None 6 None None 9 None None 12 None None 15 None None 18 None

# When I do it in a different way,
a = MultipleIterator(20, 3).__iter__()
a.__next__() # Nothing comes out
a.__next__() # Nothing comes out
a.__next__() #3 Output

python iterator

2022-09-20 08:43

1 Answers

Number 1

There are two conditional statements within the __next__ function. There are four cases, but it is not specified which one to return for one case.

Number 2

The return value of a function that ends without a return value is None. At the idle prompt, if there is a return value for the function, it displays the return value, and when None, nothing is displayed.

2022-09-20 08:43

If you have any answers or tips

© 2022 pinfo. All rights reserved.