forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bingoaddable.py
81 lines (64 loc) · 1.91 KB
/
bingoaddable.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
======================
AddableBingoCage tests
======================
Tests for __add__:
# tag::ADDABLE_BINGO_ADD_DEMO[]
>>> vowels = 'AEIOU'
>>> globe = AddableBingoCage(vowels) # <1>
>>> globe.inspect()
('A', 'E', 'I', 'O', 'U')
>>> globe.pick() in vowels # <2>
True
>>> len(globe.inspect()) # <3>
4
>>> globe2 = AddableBingoCage('XYZ') # <4>
>>> globe3 = globe + globe2
>>> len(globe3.inspect()) # <5>
7
>>> void = globe + [10, 20] # <6>
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'AddableBingoCage' and 'list'
# end::ADDABLE_BINGO_ADD_DEMO[]
Tests for __iadd__:
# tag::ADDABLE_BINGO_IADD_DEMO[]
>>> globe_orig = globe # <1>
>>> len(globe.inspect()) # <2>
4
>>> globe += globe2 # <3>
>>> len(globe.inspect())
7
>>> globe += ['M', 'N'] # <4>
>>> len(globe.inspect())
9
>>> globe is globe_orig # <5>
True
>>> globe += 1 # <6>
Traceback (most recent call last):
...
TypeError: right operand in += must be 'Tombola' or an iterable
# end::ADDABLE_BINGO_IADD_DEMO[]
"""
# tag::ADDABLE_BINGO[]
from tombola import Tombola
from bingo import BingoCage
class AddableBingoCage(BingoCage): # <1>
def __add__(self, other):
if isinstance(other, Tombola): # <2>
return AddableBingoCage(self.inspect() + other.inspect())
else:
return NotImplemented
def __iadd__(self, other):
if isinstance(other, Tombola):
other_iterable = other.inspect() # <3>
else:
try:
other_iterable = iter(other) # <4>
except TypeError: # <5>
msg = ('right operand in += must be '
"'Tombola' or an iterable")
raise TypeError(msg)
self.load(other_iterable) # <6>
return self # <7>
# end::ADDABLE_BINGO[]