Contents

要实现一个可遍历的容器,需要两步:

  1. 容器继承collection.abc.Iterable,然后实现__iter__()方法
  2. 实现一个Iterator类,继承自collection.abc.Iterator,然后实现__next__()方法

实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from collections.abc import Iterator, Iterable
from typing import Any
class ConcreteIterator(Iterator):
def __init__(self, collection):
self._collection = collection
self._position = 0
def __next__(self):
try:
value = self._collection._container[self._position]
self._position = self._position + 1
except IndexError:
raise StopIteration()
return value
class ConcreteCollection(Iterable):
def __init__(self):
self._container = []
def __iter__(self):
return ConcreteIterator(self)
def add_item(self, item: Any):
self._container.append(item)
if __name__ == "__main__":
collection = ConcreteCollection()
collection.add_item('Hello')
collection.add_item('Wolrd,')
collection.add_item('Python.')
for item in collection:
print('{} '.format(item), end='')
print('')
Contents