Iteratory niestandardowe

Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Jake Roach

Data Engineer

Iteratory

Klasy umożliwiające przechodzenie przez kolekcję obiektów lub strumień danych i zwracające jeden element na raz

  • Podobne do list i tuple, lecz działają inaczej
  • Nawigacja, transformacja, generowanie
  • Pętla for
  • Funkcja next()

$$

Protokół iteratora...

# 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
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Protokół iteratora

__iter__()

  • Zwraca iterator, w tym przypadku referencję do samego siebie
  • ... return self

$$

__next__()

  • Zwraca następną wartość z kolekcji lub strumienia danych
  • Odbywa się iteracja, transformacja i generowanie

$$

Aby klasa była iteratorem, muszą być zdefiniowane zarówno __iter__(), jak i __next__()!

Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Przykładowy iterator

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"])
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Użycie przykładowego iteratora

three_flips = CoinFlips(3)

# Flip the coin three times
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Iterowanie po iteratorze

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
...
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

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
  • Sygnalizuje koniec kolekcji/strumienia danych
  • Zapobiega nieskończonym pętlom
  • Łatwa w obsłudze
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Iterowanie po iteratorze

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
H
T
H
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Obsługa wyjątków 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!
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Czas na ćwiczenia!

Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Preparing Video For Download...