- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.py
More file actions
Latest commit
62 lines (48 loc) · 1.37 KB
/
Copy pathiterator.py
File metadata and controls
62 lines (48 loc) · 1.37 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ importannotations
fromtypingimportAny, List, Optional
# Iterator interface
classIterator:
def__init__(self, collection: MyList):
self._collection=collection
self._index=0
defhas_next(self) ->bool:
returnself._index<len(self._collection)
defnext(self) ->Optional[Any]: # getNext()
ifself.has_next():
item=self._collection[self._index]
self._index+=1
returnitem
else:
returnNone
# Aggregate interface
classAggregate:
defcreate_iterator(self) ->Iterator: # createIterator()
pass
# Concrete Aggregate
classMyList(Aggregate):
def__init__(self):
self._items: List[Any] = []
defadd_item(self, item: Any):
self._items.append(item)
def__getitem__(self, index: int) ->Any:
returnself._items[index]
def__len__(self) ->int:
returnlen(self._items)
defcreate_iterator(self) ->Iterator: # createIterator()
returnIterator(self)
# Client code
defclient_code(collection: Aggregate):
iterator=collection.create_iterator()
whileiterator.has_next():
item=iterator.next()
print(item)
# Usage
my_list=MyList()
my_list.add_item("Item 1")
my_list.add_item("Item 2")
my_list.add_item("Item 3")
client_code(my_list)
## Output
# Item 1
# Item 2
# Item 3