How to build a basic iterator?

How can I create an iterator in Python?

For example, suppose I have a class whose instances logically "contain" some values:

class Example:
    def __init__(self, values):
        self.values = values

I want to be able to write code like:

e = Example([1, 2, 3])
# Each time through the loop, expose one of the values from e.values
for value in e:
    print("The example object contains", value)

More generally, the iterator should be able to control where the values come from, or even compute them on the fly (rather than considering any particular attribute of the instance).

← Назад к списку