Iterator (iter ()) - Funktion in Python.

Für Wörterbuch kann ich @ verwenditer() zum Durchlaufen der Schlüssel des Wörterbuchs.

y = {"x":10, "y":20}
for val in iter(y):
    print val

Wenn ich den Iterator wie folgt habe,

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

Warum kann ich es nicht so benutzen

x = Counter(3,8)
for i in x:
    print x

Noc

x = Counter(3,8)
for i in iter(x):
    print x

aber so?

for c in Counter(3, 8):
    print c

Was ist die Verwendung voniter() Funktion?

HINZUGEFÜG

Ich denke, dies kann einer der Wege sein, wieiter() wird genutzt

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

class Hello:
    def __iter__(self):
        return Counter(10,20)

x = iter(Hello())
for i in x:
    print i

Antworten auf die Frage(4)

Ihre Antwort auf die Frage