I am trying to understand code that has a class to create a generator which is later iterated through with the next() built in fiction.
The class in question is this:
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 by the next() built in function. That is...
gen = Mygen()
next(gen) # Returns values
I don't understand how the class can be a generator without the __iter__()
method. Is the
__iter__()
method necessary to produce a generator from a class? Everywhere I search it seems that __iter__()
and __next__()
are used together to create a generator from a class.
I'm fairly new to Python. This code sample was my best attempt at showing where the problem for me is, as the actual code does a lot more and would detract from the question and be too long to put here. I'm not experience enough to know how to shorten it more than this or more info is required.