另一种选择是从适当的抽象基类继承自`集合模块记录在这里。
如果容器是其自己的迭代器,则可以从继承
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
注意:感谢Glenn Maynard提请我注意需要澄清一方面迭代器与另一方面是可迭代容器而不是迭代器的容器之间的区别。