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

(singke) #1
19: #Initialize subclass data attributes
20: self.__migratory = 'yes' #Migratory bird.
21: self.__flock_size = flock_size #How many in flock.
22:
23:
24: #Mutator methods for Barn Swallow data attributes
25: def set_flock_size(self,flock_size): #No. of birds in sighting
26: self.__flock_size = flock_size
27:
28: #Accessor methods for Barn Swallow data attributes
29: def get_migratory(self):
30: return self.__migratory
31: def get_flock_size(self):
32: return self.__flock_size
33: pi@raspberrypi ~ $

You can see a partial listing of the Bird base class object definition file on lines 2 through 7 of
Listing 15.2. The BarnSwallow subclass object definition is on lines 8 through 32 of the
birds.py object module file.


Watch Out!: Proper Indentation
Remember that you need to make sure you do the indentation properly for an object
module file! If you do not indent object module blocks properly, Python gives you an
error message, indicating that it cannot find a method or data attribute.

Inheritance allows you to use a subclass along with its base class in a module file. However, you are
not limited to just one subclass in an object module file.


Adding Additional Subclasses


You can add additional subclass object definitions to an object module file. For example, the South
African cliff swallow is very similar to a barn swallow, but it is non-migratory.


Listing 15.3 adds the SouthAfricanCliffSwallow subclass. Again, it is an oversimplified
version of a bird. However, you can see that the subclass object definition has its own place within
the object module file. You could list every subclass of bird that exists in the file birds.py, if you
wanted to.


LISTING 15.3 The CliffSwallow Subclass in the Bird Object 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: ...
8:
9: #
10: # Barn Swallow subclass (base class: Bird)
11: #
Free download pdf