Lập trình Hướng đối tượng Nâng cao với Python
Jake Roach
Data Engineer
Các lớp cho phép duyệt qua bộ sưu tập hoặc dòng dữ liệu và trả về từng phần tử một
list, tuple, nhưng hành vi khácfornext()$$
Giao thức iterator...
# Bộ sưu tập
chuck = NameIterator("Charles Carmicheal")
for letter in chuck:
print(letter)
C
h
u
...
# Dòng dữ liệu
fun_game = DiceGame(rolls=3)
next(fun_game) # ... v.v.
4
__iter__()
... return self$$
__next__()
$$
Cả __iter__() và __next__() phải được định nghĩa để một lớp được xem là iterator!
class CoinFlips:
def __init__(self, number_of_flips):
self.number_of_flips = number_of_flips # Lưu tổng số lần tung
self.counter = 0
def __iter__(self):
return self # Trả về tham chiếu của iterator
# Tung đồng xu kế tiếp, trả về kết quả
def __next__(self):
if self.counter < self.number_of_flips:
self.counter += 1
return random.choice(["H", "T"])
three_flips = CoinFlips(3)
# Tung đồng xu ba lần
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
three_flips = CoinFlips(3)
# Bây giờ, thử lặp qua mọi phần tử của bộ lặp
for flip in three_flips:
print(flip)
T
H
T
None
None
None
...
...
def __next__(self):
# Chỉ làm nếu đồng xu chưa được tung "number_of_flips" lần
if self.counter < self.number_of_flips:
self.counter += 1
return random.choice(["H", "T"])
else: # Nếu không, kết thúc bằng StopIteration
raise StopIteration
three_flips = CoinFlips(3)
# Bây giờ, thử lặp qua mọi phần tử của bộ lặp
for flip in three_flips:
print(flip)
H
T
H
while True:
try:
next(three_flips) # Lấy phần tử kế tiếp của three_flips
# Bắt ngoại lệ StopIteration
except StopIteration:
print("Hoàn tất mọi lần tung!")
break
H
H
H
Hoàn tất mọi lần tung!
Lập trình Hướng đối tượng Nâng cao với Python