The basics. Here’s the solution we coded up for this exercise, along with some interactive tests. The __
add__ overload has to appear only once, in the superclass. Notice that you get an error for expressions where a class instance appears on the right of a+; to fix this, use __radd__ methods also (an advanced topic we skipped; see other Python books and/or Python reference manuals for more details). You could also write theaddmethod to take just two arguments, as shown in the chapter’s examples.%
cat adder.pyclass Adder: def add(self, x, y): print 'not implemented!' def __init__(self, start=[]): self.data = start def __add__(self, other): return self.add(self.data, other) # or in subclasses--return type? class ListAdder(Adder): def add(self, x, y): return x + y class DictAdder(Adder): def add(self, x, y): new = {} for k in x.keys(): new[k] = x[k] for k in y.keys(): new[k] = y[k] return new %python>>>from adder import *>>>x = Adder()>>>x.add(1, 2)not implemented! >>>x = ListAdder()>>>x.add([1], [2])[1, 2] >>>x = DictAdder()>>>x.add({1:1}, {2:2}){1: 1, 2: 2} >>>x = Adder([1])>>>x + [2]not implemented! >>> >>>x = ListAdder([1])>>>x + [2][1, 2] >>>[2] + xTraceback (innermost last): File "<stdin>", line 1, in ? TypeError: __add__ nor __radd__ defined for these operandsOperator overloading. Here’s what we came up with for this one. It uses a few operator overload methods we didn’t say much about, but they should be straightforward to understand. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access