From 9252eb99e38d9a5c5b49145daccfe04927acaf93 Mon Sep 17 00:00:00 2001 From: Vivien Engling Date: Thu, 5 Nov 2026 13:33:38 +0100 Subject: [PATCH] modified --- 01_verdoppeln.py | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/01_verdoppeln.py b/01_verdoppeln.py index e6d3acb..7ab7279 100644 --- a/01_verdoppeln.py +++ b/01_verdoppeln.py @@ -1,3 +1,33 @@ -numbers = [1, 2, 3, 4, 5] -result = list(map(lambda x: x * 2, [1, 2, 3, 4, 5])) -print(result) \ No newline at end of file +# __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". \ No newline at end of file