1. 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 the add method to take just two arguments, as shown in the chapter’s examples.

    % cat adder.py
    
    class 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] + x
    Traceback (innermost last):
      File "<stdin>", line 1, in ?
    TypeError: __add__ nor __radd__ defined for these operands
  2. Operator 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. ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.