Page 59 - Programming the Raspberry Pi Getting Started with Python
P. 59
command. However, it is always worth checking the instructions first to see if there’s anything else
you need to do. To see the instructions, type more INSTALL.txt.
Good thing you checked! The instructions state that you need to do the following:
Finally, you are ready to run the module installer itself:
Once the module is installed, you will be able to import it from the Python Shell.
Object Orientation
Object orientation has much in common with modules. It shares the same goals of trying to group
related items together so that they are easy to maintain and find. As the name suggests, object
orientation is about objects. We have been unobtrusively using objects already. A string is an object,
for example. Thus, when we type
We are telling the string 'abc' that we want a copy of it, but in uppercase. In object-oriented terms,
abc is an instance of the built-in class str and upper is a method on the class str.
We can actually find out the class of an object, as shown here (note double underscores before and
after the word class):
Defining Classes
That’s enough of other people’s classes; let’s make some of our own. We are going to start by creating
a class that does the job of converting measurements from one unit to another by multiplying a value
by a scale factor.
We will give the class the catchy name ScaleConverter. Here is the listing for the whole class,
plus a few lines of code to test it:
This requires some explanation. The first line is fairly obvious: It states that we are beginning the
definition of a class called ScaleConverter. The colon (:) on the end indicates that all that follows is
part of the class definition until we get back to an indent level of the left margin again.
Inside the ScaleConverter, we can see what look like three function definitions. These functions