Giải thích
Iterator là đối tượng trong Python thực hiện iteration protocol. Tuple, list, set gọi là built-in iterators trong Python. Có hai loại phương thức trong iteration protocol.
__iter__(): Phương thức này được gọi khi khởi tạo iterator và phải trả về đối tượng có phương thức next() hoặc __next__() (Python 3).
next() hoặc __next__() (Python 3): Phương thức này trả về phần tử tiếp theo từ sequence iteration. Khi iterator dùng với for loop, for loop trực tiếp gọi next() trên đối tượng iterator.
Ví dụ mã
# Tạo custom iterator class
class Pow_of_Two:
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration("Message")
a = Pow_of_Two(4)
i = iter(a)
print(i.__next__())
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
Kết quả
1 2 4 8 16 StopIteration error will be raised