कस्टम Iterators

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

Iterators

ऐसी classes जो ऑब्जेक्ट्स के कलेक्शन या डेटा स्ट्रीम को ट्रैवर्स करने दें, और एक बार में एक आइटम लौटाएँ

  • list, tuple जैसे, पर व्यवहार अलग
  • Navigate, transform, generate
  • for लूप से iterate करें
  • next() फंक्शन

$$

Iterator protocol...

# 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
Intermediate Object-Oriented Programming in Python

Iterator protocol

__iter__()

  • एक iterator लौटाता है, यहाँ self का ही रेफरेंस
  • ... return self

$$

__next__()

  • कलेक्शन या डेटा स्ट्रीम में से अगला मान लौटाता है
  • यहीं iteration, transformation, और generation होती है

$$

किसी class को iterator मानने के लिए __iter__() और __next__() दोनों परिभाषित होने चाहिए!

Intermediate Object-Oriented Programming in Python

उदाहरण iterator

class CoinFlips:
    def __init__(self, number_of_flips):
        self.number_of_flips = number_of_flips  # कुल फ्लिप्स संग्रहीत करें
        self.counter = 0

    def __iter__(self):
        return self  # iterator का रेफरेंस लौटाएँ

    # अगला सिक्का उछालें और आउटपुट लौटाएँ
    def __next__(self):
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])
Intermediate Object-Oriented Programming in Python

उदाहरण iterator का उपयोग

three_flips = CoinFlips(3)

# सिक्का तीन बार उछालें
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Intermediate Object-Oriented Programming in Python

Iterator पर लूप करना

three_flips = CoinFlips(3)

# अब, iterator के हर एलिमेंट पर लूप करें
for flip in three_flips:
    print(flip)
T
H
T
None
None
None
...
Intermediate Object-Oriented Programming in Python

StopIteration

...
    def __next__(self):
        # तभी करें जब सिक्का अभी "number_of_flips" बार से कम उछला हो
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])

        else:  # अन्यथा, StopIteration के साथ रोक दें
            raise StopIteration
  • कलेक्शन/डेटा स्ट्रीम की समाप्ति का संकेत
  • अनंत लूप रोकता है
  • संभालना आसान
Intermediate Object-Oriented Programming in Python

Iterator पर लूप करना

three_flips = CoinFlips(3)

# अब, iterator के हर एलिमेंट पर लूप करें
for flip in three_flips:
    print(flip)
H
T
H
Intermediate Object-Oriented Programming in Python

StopIteration exceptions को संभालना

while True:
    try:
        next(three_flips)  # three_flips से अगला एलिमेंट लें

    # StopIteration exception पकड़ें
    except StopIteration:
        print("Completed all coin flips!")
        break
H
H
H
Completed all coin flips!
Intermediate Object-Oriented Programming in Python

अभ्यास करते हैं!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...