File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff 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 |
Original file line number Diff line number Diff line change 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 ()
You can’t perform that action at this time.
0 commit comments