Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

B. Solutions to End-of-Part Exercises > Part VI, Classes and OOP

Part VI, Classes and OOP

See Test Your Knowledge: Part VI Exercises in Chapter 31 for the exercises.

  1. Inheritance. Here’s the solution code for this exercise (file adder.py), along with some interactive tests. The __add__ overload has to appear only once, in the superclass, as it invokes type-specific add methods in subclasses:

    class Adder:
        def add(self, x, y):
            print('not implemented!')
        def __init__(self, start=[]):
            self.data = start
        def __add__(self, other):                    # Or in subclasses?
            return self.add(self.data, other)        # Or 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

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


 Â