This commit is contained in:
englingvi103466 committed 2026-11-05 13:33:38 +01:00
1 parent ecb59a6571
commit 9252eb99e3
1 file changed
+33 -3
+33 -3
View File
@@ -1,3 +1,33 @@
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, [1, 2, 3, 4, 5]))
print(result)
# __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".