1

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
  • 3
    Look into the __iter__ magic method iter Commented Aug 11, 2016 at 6:51

1 Answer 1

7

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.