迭代器模式,不一次性直接返回结果,调用一次方法,返回一个。
class Iterator(object):
def __init__(self, iterator_list):
super().__init__()
self.list = iterator_list
self.current_index = 0
self.max_index = 0
def __iter__(self):
self.current_index = 0
self.max_index = len(self.list) - 1
return self
def __next__(self):
if self.current_index <= self.max_index:
one = self.list[self.current_index]
self.current_index += 1
return one
else:
raise StopIteration
def main():
iterator = Iterator([5, 9, 7, 'x', 'e'])
for one in iterator:
print(one)
if __name__ == '__main__':
main()
本文详细探讨了Python中的迭代器模式,它允许不一次性加载所有数据,而是按需逐个返回结果。迭代器模式在处理大量数据时能有效节省内存,提高程序效率。
457

被折叠的 条评论
为什么被折叠?



