A class generator without the __iter __ () method, but the object instance works with the following ()

I am trying to understand the code that a class has for creating a generator, which is later repeated using the following () inline fiction.

The corresponding class is as follows:

Class MyGen():
    def __init__(self):
    """ Define some instance attributes"""
        self.foo = 'bar'
        self.some_attribute = 0
    def __next__(self):
        if self.some_attribute < some_condition:
            new_value = self.argument1
            self.some_attribute += 1
            return new_value

In a global function, the returned object gets iterated through the following () built-in function. It...

gen = Mygen()
next(gen) # Returns values

I do not understand how a class can be a generator without a method __iter__(). Is this the   __iter__()method needed to create a generator from a class? Wherever I look, it seems that __iter__()they __next__()are used together to create a generator from a class.

Python. , , , . , , , .

+4
2

next(x) x.__next__() .

, __next__ gen, "" .

, ( ).

+3

__iter__ . , , iter() (, for i in obj:)

- - __next__, iterable StopIteration, . next() (, for)

, , , , , . __next__ __iter__, self.

+1

Source: https://habr.com/ru/post/1609518/


All Articles