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

(singke) #1

However, there are more insects than just ants. For example, the honey bee is also an insect. It shares
the first characteristic specific to an ant (narrow abdomen). Therefore, to create a honey bee object
definition, you would need to duplicate the characteristics from the insect object definition, duplicate
the first ant characteristic from the ant object definition file, and then add the honey bee’s unique
characteristics. That is a lot of duplication!


The class problem is strongly demonstrated in the three object definitions we’ve just look at (insects,
ants, and honey bees). And there are more insects besides honey bees and ants! To fix the inefficient
duplication class problem, Python uses subclasses and inheritance.


Understanding Subclasses and Inheritance


A subclass is an object definition. It has all the data attributes and methods of another class but
includes additional attributes and methods specific to itself. These additional data attributes and
methods make a subclass a specific version of a class. For example, an ant is a specific version of an
insect.


A class whose data attributes and methods are used by a subclass is called a superclass. Using the
insect example, the superclass would be Insect, and the subclass would be Ant. An ant has all the
characteristics of an insect, as well as a few of its own, which are specific to ants.


By the Way: Object Class Terms
A superclass, also called a base class, is a class used in an object definition of a
subclass. A subclass, which has all the data attributes and methods of a base class, as
well as a few of its own, is also called a derived class.

Subclasses have what is called an “is a” relationship to their base class. For example, an ant
(subclass) is an insect (base class). A honey bee (subclass) is an insect (base class). These are some
other examples of “is a” relationships:


A duck is a bird.
Python is a programming language.
A Raspberry Pi is a computer.

In order for a subclass object to gain the data attributes and methods of its base class, Python uses a
process called inheritance. In Python, inheritance is more similar to inheriting genes from your
biological parents than receiving a monetary inheritance.


Inheritance is the process by which a subclass may obtain a copy of the base class’s data attributes
and methods to include in its object class definition. The subclass object then creates its own data
attributes and methods in its object class definition, to make itself a specialized version of the base
class.


The example of ants and insects can be used to demonstrate inheritance. To keep it simple, only
characteristics (data attributes) are used. But you could use behavior (methods) here, too! An insect
base class object definition would contain the following data attributes:


backbone='none'
exoskeleton='chitinous'
body='three-part'
Free download pdf