33 lines
1004 B
Python
33 lines
1004 B
Python
# __iter__(self): Gibt das Iterator-Objekt selbst zurück (return self).
|
|
|
|
# __next__(self): Gibt das nächste Element zurück. Wenn das Ende erreicht ist,
|
|
# wirft die Methode eine StopIteration-Exception.
|
|
|
|
class Squares:
|
|
|
|
def __init__(self, limit):
|
|
self.limit = limit
|
|
self.current = 1
|
|
|
|
def __iter__(self):
|
|
return self
|
|
|
|
def __next__(self):
|
|
if self.current > self.limit:
|
|
raise StopIteration
|
|
result = self.current**2
|
|
self.current += 1
|
|
return result
|
|
|
|
|
|
# Testen
|
|
sq = Squares(4)
|
|
print(list(sq)) # Ausgabe: [1, 4, 9, 16]
|
|
|
|
# Zweiter Durchlauf
|
|
print(list(sq)) # Ausgabe: []
|
|
|
|
# Beim ersten Durchlauf wird der interne Zustand self.current schrittweise bis auf 5 erhöht.
|
|
# Beim zweiten Durchlauf steht self.current immer noch auf 5 (welches größer als limit = 4 ist).
|
|
# Die __next__-Methode wirft sofort erneut eine StopIteration-Exception, weshalb das Ergebnis
|
|
# beim zweiten Mal eine leere Liste [] ist. Iteratoren sind in Python grundsätzlich "einmalig erschöpfbar". |