另一种选择是从 `collections 模块中的适当抽象基类继承 here。
如果容器是它自己的迭代器,你可以继承自
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 提请我注意需要澄清迭代器与可迭代容器之间的区别,另一方面是迭代器。