Intermediate Object-Oriented Programming in Python
Jake Roach
Data Engineer
ऐसी classes जो ऑब्जेक्ट्स के कलेक्शन या डेटा स्ट्रीम को ट्रैवर्स करने दें, और एक बार में एक आइटम लौटाएँ
list, tuple जैसे, पर व्यवहार अलग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
__iter__()
... return self$$
__next__()
$$
किसी class को iterator मानने के लिए __iter__() और __next__() दोनों परिभाषित होने चाहिए!
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"])
three_flips = CoinFlips(3)
# सिक्का तीन बार उछालें
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
three_flips = CoinFlips(3)
# अब, iterator के हर एलिमेंट पर लूप करें
for flip in three_flips:
print(flip)
T
H
T
None
None
None
...
...
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
three_flips = CoinFlips(3)
# अब, iterator के हर एलिमेंट पर लूप करें
for flip in three_flips:
print(flip)
H
T
H
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