Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Hour 15. Employing Inheritance


What You’ll Learn in This Hour:
What subclasses are
What inheritance is
How to use inheritance in Python
Inheritance in scripts

In this hour, you will learn about subclasses and inheritance, including how to create subclasses and
how to use inheritance in scripts. Inheritance is the next step in understanding object-oriented
programming in Python.


Learning About the Class Problem


In Hour 14, “Exploring the World of Object-Oriented Programming,” you read about object-oriented
programming, classes, and class module files. Even with object-oriented programming, problems
related to duplication of object data attributes and methods still exist. This is called the “class
problem.” This hour looks at the biological classification of animals and plants to help clarify the
nature of the class problem.


Suppose you are creating a Python script for an insect scientist (entomologist). What makes an insect
an insect? A very basic classification for an insect is that an animal must have the following in order
to be considered an insect:


No vertebral column (backbone)
A chitinous exoskeleton (outside shell)
A three-part body (head, thorax, and abdomen)
Three pairs of jointed legs
Compound eyes
One pair of antennae

Using this information, you could create an insect object definition. It would include these
characteristics as part of the object module.


But think about the ant. An ant is classified as part of the insect class because it has all the
characteristics just listed. However, an ant also has these unique characteristics that not all other
insects share:


A narrow abdomen where it joins the thorax (looks like a tiny waist)
At the narrow abdomen where it joins the thorax, a hump on top that is clearly separate from the
rest of the abdomen
Elbowed antennae, with a long first segment

Thus, to create an object definition for an ant, you would need to duplicate all the insect
characteristics that are put into the insect object definition. In addition, you must add the
characteristics that are specific to ants.

Free download pdf