別のオプションは、ここで説明されているように、 `collectionsモジュールから適切な抽象基本クラスを継承することです。
コンテナが独自のイテレータである場合、から継承できます
collections.Iterator。nextその後、メソッドを実装するだけで済みます。
例は次のとおりです。
>>> from collections import Iterator
>>> class MyContainer(Iterator):
... def __init__(self, *data):
... self.data = list(data)
... def next(self):
... if not self.data:
... raise StopIteration
... return self.data.pop()
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
4.0
3
two
1
あなたが見ている間collections、モジュール、継承を検討しSequence、Mappingそれがより適切であるかどうか、別の抽象基本クラス。次にSequenceサブクラスの例を示します。
>>> from collections import Sequence
>>> class MyContainer(Sequence):
... def __init__(self, *data):
... self.data = list(data)
... def __getitem__(self, index):
... return self.data[index]
... def __len__(self):
... return len(self.data)
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
1
two
3
4.0
NB:一方のイテレータと、もう一方のイテレータではなくイテラブルであるコンテナの違いを明確にする必要性に注意を向けてくれたGlenn Maynardに感謝します。