Python Glossary Русский

all Python 3Iterators & generatorsfunction

__iter__

iterator protocol

The method iter(obj) and the for loop call: it returns an iterator over the object.

Syntax

def __iter__(self): ...

On an iterable, __iter__ returns a fresh iterator each time, which is why a list can be looped over many times. On an iterator itself, __iter__ returns self — so an iterator also works in for, but only once. A convenient way to write __iter__ is as a generator with yield.

Examples

class Countdown:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        for i in range(self.n, 0, -1):
            yield i
c = Countdown(3)
print(list(c))  # → [3, 2, 1]
print(list(c))  # → [3, 2, 1] — новый итератор при каждом обходе

See also

Open in the full glossarydocs.python.orgReport an inaccuracy