Iteratori personalizați

Programare orientată pe obiecte intermediară în Python

Jake Roach

Data Engineer

Iteratori

Clase care permit parcurgerea unei colecții de obiecte sau a unui flux de date și returnează câte un element pe rând

  • Similari cu list-urile și tuple-urile, dar se comportă diferit
  • Navigare, transformare, generare
  • Parcurși cu bucle for
  • Funcția next()

$$

Protocolul iteratorului...

# Collection
chuck = NameIterator("Charles Carmicheal")
for letter in chuck:
    print(letter)
C
h
u
...
# Data stream
fun_game = DiceGame(rolls=3)
next(fun_game)  # ... and so on
4
Programare orientată pe obiecte intermediară în Python

Protocolul iteratorului

__iter__()

  • Returnează un iterator, în acest caz o referință la sine însuși
  • ... return self

$$

__next__()

  • Returnează următoarea valoare din colecție sau fluxul de date
  • Se efectuează iterarea, transformarea și generarea

$$

Atât __iter__(), cât și __next__() trebuie definite pentru ca o clasă să fie considerată iterator!

Programare orientată pe obiecte intermediară în Python

Iterator exemplu

class CoinFlips:
    def __init__(self, number_of_flips):
        self.number_of_flips = number_of_flips  # Store the total number of flips
        self.counter = 0

    def __iter__(self):
        return self  # Return a reference of the iterator

    # Flip the next coin, return the output
    def __next__(self):
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])
Programare orientată pe obiecte intermediară în Python

Utilizarea unui iterator exemplu

three_flips = CoinFlips(3)

# Flip the coin three times
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Programare orientată pe obiecte intermediară în Python

Iterare printr-un iterator

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
T
H
T
None
None
None
...
Programare orientată pe obiecte intermediară în Python

StopIteration

...
    def __next__(self):
        # Only do this if the coin hasn't been flipped "number_of_flips" times
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])

        else:  # Otherwise, stop execution with StopIteration
            raise StopIteration
  • Semnalizează sfârșitul colecției/fluxului de date
  • Previne buclele infinite
  • Ușor de gestionat
Programare orientată pe obiecte intermediară în Python

Iterare printr-un iterator

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
H
T
H
Programare orientată pe obiecte intermediară în Python

Gestionarea excepțiilor StopIteration

while True:
    try:
        next(three_flips)  # Pull the next element of three_flips

    # Catch a stop iteration exception
    except StopIteration:
        print("Completed all coin flips!")
        break
H
H
H
Completed all coin flips!
Programare orientată pe obiecte intermediară în Python

Să exersăm!

Programare orientată pe obiecte intermediară în Python

Preparing Video For Download...