I am writing something similar to an array, but with some tweaks. Of course, it should be iterable. But I do not really want to make another object as an iterator, and 'for I in myObject.generator()' seems too clunky for me. Is there any way to make a generator function that would work for 'for I in myObject'?
1 Answer
Just use a generator function for the __iter__ method:
def __iter__(self):
for value in self._values:
yield value
This produces a new generator iterator object each time iter() is called on the object (which is what for does for you when you use your object in a loop).
__iter__magic method iter