百科定义:在 面向对象编程里,迭代器模式是一种设计模式,是一种最简单也最常见的设计模式。它可以让用户透过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
public interface Iterator {
boolean hasNext();
String next();
}
代码实现:
class Iter():
context = ["A", "B", "C", "D", "F"]
def __init__(self, begin, end):
self.index = begin
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.index >= len(Iter.context):
raise StopIteration
current = self.index
self.index += 1
return Iter.context[current]
# def next(self):
# try:
# while self.index < len(Iter.context):
# yield Iter.context[self.index]
# self.index += 1
# except StopIteration:
# raise "StopIteration"
if __name__ == "__main__":
it = Iter(0, 5)
for i in it:
print(i)
# 函数是生成器
# it_1 =Iter(0,5)
# for i in it_1.next():
# print(i)
def go(index):
context = ["A", "B", "C", "D"]
yield context[:index]
def iter_go():
return go(2)
def iter_go_4():
return go(4)
if __name__ == "__main__":
for i in iter_go():
print(i)