Page 60 - Programming the Raspberry Pi Getting Started with Python
P. 60
belong to the class; they cannot be used except via an instance of the class. These kinds of functions
that belong to a class are called methods.
The first method, __init__, looks a bit strange—its name has two underscore characters on either
side. When Python is creating a new instance of a class, it automatically calls the method __init__.
The number of parameters that __init__ should have depends on how many parameters are supplied
when an instance of the class is made. To unravel that, we need to look at this line at the end of the
file:
This line creates a new instance of the ScaleConverter, specifying what the units being converted
from and to are, as well as the scaling factor. The __init__ method must have all these parameters,
but it must also have a parameter called self as the first parameter:
The parameter self refers to the object itself. Now, looking at the body of the __init__ method,
we see some assignments:
Each of these assignments creates a variable that belongs to the object and has its initial value set
from the parameters passed in to __init__.
To recap, when we create a new ScaleConverter by typing something like
Python creates a new instance of ScaleConverter and assigns the values 'inches', 'mm', and 25 to
its three variables: self.units_from, self.units_to, and self.factor.
The term encapsulation is often used in discussions of classes. It is the job of a class to encapsulate
everything to do with the class. That means storing data (like the three variables) and things that you
might want to do with the data in the form of the description and convert methods.
The first of these (description) takes the information that the Converter knows about its units
and creates a string that describes it. As with __init__, all methods must have a first parameter of
self. The method will probably need it to access the data of the class to which it belongs.
Try it yourself by running program 05_01_converter.py and then typing the following in the Python
Shell:
The convert method has two parameters: the mandatory self parameter and a parameter called
value. The method simply returns the result of multiplying the value passed in by self.scale:
Inheritance
The ScaleConverter class is okay for units of length and things like that; however, it would not work
for something like converting temperature from degrees Celsius (C) to degrees Fahrenheit (F). The
formula for this is F = C * 1.8 + 32. There is both a scale factor (1.8) and an offset (32).
Let’s create a class called ScaleAndOffsetConverter that is just like ScaleConverter, but with a
factor as well as an offset. One way to do this would simply be to copy the whole of the code for
ScaleConverter and change it a bit by adding the extra variable. It might, in fact, look something like
this: