Python迭代模式实例详解
程序员文章站
2022-04-05 23:51:59
...
本文主要和大家分享Python迭代模式实例详解,主要以代码的形式和大家分享,希望能帮助到大家。
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 11:43:05 2018 @author: mz """ class Iterator(object): def Next(self): pass def HasNext(self): pass def First(self): pass def Forward(self): pass class CocreteIterator(Iterator): def __init__(self, aggregate): self._aggregate = aggregate def Next(self): return self._aggregate.Next() def HasNext(self): return self._aggregate.HasNext() def First(self): return self._aggregate.First() def Forward(self): return self._aggregate.Forward() class Aggregate(object): def CreateIterator(self): pass def Next(self): pass def HasNext(self): pass def First(self): pass def Attach(self, obj): pass def Forward(self): pass class ConcreteAggregate(object): def __init__(self): self._lst = [] self._index = 0 def CreateIterator(self): return CocreteIterator(self) def Next(self): return self._lst[self._index] def HasNext(self): return self._index < len(self._lst) def First(self): self._index = 0 return self._lst[0] def Attach(self, obj): self._lst.append(obj) def Forward(self): self._index += 1 if "__main__" == __name__: aggregate = ConcreteAggregate() aggregate.Attach(1) aggregate.Attach("2") aggregate.Attach("a") aggregate.Attach("b") aggregate.Attach("c") aggregate.Attach("45") it = aggregate.CreateIterator() while it.HasNext(): print(it.Next()) it.Forward()
运行结果:
1 2 a b c 45
以上就是Python迭代模式实例详解的详细内容,更多请关注其它相关文章!
上一篇: 通过css布局完成div位置的存放实例
下一篇: 什么是决策树算法?