另一个选择是从`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提醒我需要澄清迭代器与可迭代容器之间的区别。
some_list
中的所有元素都被生成时。 - laike9mreturn
或者到达函数结尾(和其他所有函数一样,在结尾有一个隐含的return None
)返回时,Python 会自动引发StopIteration
异常。明确引发StopIteration
不是必需的,并且在 Python 3.5 中实际上不起作用(请参见 PEP 479): 就像生成器将return
转换为StopIteration
一样,它们也会将明确引发的raise StopIteration
转换为RuntimeError
。 - Arthur Tacca