jointed_leg_pairs=3
eyes='compound'
antennae_pair=1
The ant object class definition would inherit all six of these insect data attributes. The following three
data attributes would be added to make the subclass (ant object) a specialized version of the base
class (insect object):
abdomen_thorax_width='narrow'
abdomen_thorax_shape='humped'
antennae='elbowed'
The ant “is a” insect relationship would be maintained. Basically, the ant “inherits” the insect’s
object definition. There is no need to create duplicate data attributes and methods in the ant’s object
definition. Thus, the class problem is solved.
Using Inheritance in Python
So what does inheritance look like in Python? This is the basic syntax for inheritance in a class object
definition:
Click here to view code image
class classname:
base class data attributes
base class mutator methods
base class accessor methods
class classname (base class name):
subclass data attributes
subclass mutator methods
subclass accessor methods
Listing 15.1 shows a bird class object definition stored in the object module
/home/pi/py3prog/birds.py. The Bird class is an overly simplified object definition for a
bird. Notice that there are three immutable data attributes: feathers (line 7), bones (line 8), and
eggs (line 9). The only mutable data attribute is sex (line 10) because a bird can be male, female, or
unknown.
LISTING 15.1 Bird Object Definition File
Click here to view code image
1: pi@raspberrypi ~ $ cat /home/pi/py3prog/birds.py
2: # Bird base class
3: #
4: class Bird:
5: #Initialize Bird class data attributes
6: def __init__(self, sex):
7: self.__feathers = 'yes' #Birds have feathers
8: self.__bones = 'hollow' #Bird bones are hollow
9: self.__eggs = 'hard-shell' #Bird eggs are hard-shell.
10: self.__sex = sex #Male, female, or unknown.
11:
12: #Mutator methods for Bird data attributes