To put a subclass in its own object module file, you need to add an import Python statement to the
file, as shown in Listing 15.5. Here the Bird base class is imported before the BarnSwallow
subclass is defined.
LISTING 15.5 The BarnSwallow Subclass Object File
Click here to view code image
1: pi@raspberrypi ~ $ cat /home/pi/py3prog/barnswallow.py
2: #
3: # BarnSwallow subclass (base class: Bird)
4: #
5: from birds import Bird #import Bird base class
6:
7: class BarnSwallow(Bird):
8:
9: #Initialize Barn Swallow data attributes & obtain Bird inheritance.
10: def __init__(self, sex, flock_size):
11:
12: #Obtain base class data attributes & methods (inheritance)
13: Bird.__init__(self, sex)
14:
15: #Initialize subclass data attributes
16: self.__migratory = 'yes' #Migratory bird.
17: self.__flock_size = flock_size #How many in flock.
18:
19:
20: #Mutator methods for Barn Swallow data attributes
21: def set_flock_size(self, flock_size): #No. of birds in sighting
22: self.__flock_size = flock_size
23:
24: #Accessor methods for Barn Swallow data attributes
25: def get_migratory(self):
26: return self.__migratory
27: def get_flock_size(self):
28: return self.__flock_size
29: pi@raspberrypi ~ $
You can see in Listing 15.5 that the Bird base class is imported on line 5. Notice that the import
statement uses the from module_file_name import object_def format. It does so because the
module file name is bird.py and the object definition is called Bird. After it is imported, the
BarnSwallow subclass is defined on lines 7 through 28.
Once you have your object module files created—one containing the base class and others containing
all the necessary subclasses—the next step is to use these files in Python scripts.
Using Inheritance in Python Scripts
Using inheritance in a Python script is really not much different from using regular base class objects
in a script. Both the BarnSwallow subclass and the SouthAfricanCliffSwallow subclass
are used in script1501.py, along with their Bird base class. The script, as shown in Listing
15.6, simply goes through the objects and displays the immutable settings of each.
LISTING 15.6 Python Statements in script1501.py