Page 61 - Programming the Raspberry Pi Getting Started with Python
P. 61

Assuming we want both types of converters in the program we are writing, then this is a bad way of
          doing  it. It’s bad because we are repeating code. The description method is actually identical, and
          __init__ is almost the same. A much better way is to use something called inheritance.
             The idea behind inheritance in classes is that when you want a specialized version of a class that
          already  exists,  you  inherit  all  the  parent  class’s  variables  and  methods  and  just  add  new  ones  or
          override the ones that are different. Figure 5-2 shows a class diagram for the two classes, indicating
          how ScaleAndOffsetConverter  inherits  from ScaleConverter, adds a new variable (offset),  and
          overrides the method convert (because it will work a bit differently).





















          Figure 5-2    An example of using inheritance
             Here is the class definition for ScaleAndOffsetConverter using inheritance:












             The  first  thing  to  notice  is  that  the  class  definition  for ScaleAndOffsetConverter  has
          ScaleConverter in parentheses immediately after it. That is how you specify the parent class for a
          class.

             The __init__  method  for  the  new  “subclass”  of ScaleConverter  first  invokes  the __init__
          method  of ScaleConverter  before  defining  the  new  variable offset.  The convert  method  will
          override the convert method in the parent class because we need to add on the offset for this kind of
   56   57   58   59   60   61   62   63   64   65   66