Skip to content

Commit 2fdbac5

Browse files
committed
Added alternative implementation for Iterator pattern using the Iterator protocol
1 parent 937a4ed commit 2fdbac5

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ __Behavioral Patterns__:
4242
| [chaining_method](patterns/behavioral/chaining_method.py) | continue callback next object method |
4343
| [command](patterns/behavioral/command.py) | bundle a command and arguments to call later |
4444
| [iterator](patterns/behavioral/iterator.py) | traverse a container and access the container's elements |
45+
| [iterator](patterns/behavioral/iterator_alt.py) (alt. impl.)| traverse a container and access the container's elements |
4546
| [mediator](patterns/behavioral/mediator.py) | an object that knows how to connect other objects and act as a proxy |
4647
| [memento](patterns/behavioral/memento.py) | generate an opaque token that can be used to go back to a previous state |
4748
| [observer](patterns/behavioral/observer.py) | provide a callback for notification of events/changes to data |

patterns/behavioral/iterator_alt.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Implementation of the iterator pattern using the iterator protocol from Python
3+
4+
*TL;DR
5+
Traverses a container and accesses the container's elements.
6+
"""
7+
8+
9+
class NumberWords:
10+
"""Counts by word numbers, up to a maximum of five"""
11+
_WORD_MAP = (
12+
'one',
13+
'two',
14+
'three',
15+
'four',
16+
'five',
17+
)
18+
19+
def __init__(self, start, stop):
20+
self.start = start
21+
self.stop = stop
22+
23+
def __iter__(self): # this makes the class an Iterable
24+
return self
25+
26+
def __next__(self): # this makes the class an Iterator
27+
if self.start > self.stop or self.start > len(self._WORD_MAP):
28+
raise StopIteration
29+
current = self.start
30+
self.start += 1
31+
return self._WORD_MAP[current - 1]
32+
33+
34+
# Test the iterator
35+
36+
def main():
37+
"""
38+
# Counting to two...
39+
>>> for number in NumberWords(start=1, stop=2):
40+
... print(number)
41+
one
42+
two
43+
44+
# Counting to five...
45+
>>> for number in NumberWords(start=1, stop=5):
46+
... print(number)
47+
one
48+
two
49+
three
50+
four
51+
five
52+
"""
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
58+
doctest.testmod()

0 commit comments

Comments
 (0)