File: class/Workbook/Exercises/Lab6/ex1.txt
% 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