この記事では、主にコードの形で 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 反復モードの例の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。