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

(singke) #1
12: class BarnSwallow(Bird):
13:
14: #Initialize Barn Swallow data attributes & obtain Bird inheritance.
15: def __init__(self, sex, flock_size):
16: ...
17: #
18: # South Africa Cliff Swallow subclass (base class: Bird)
19: #
20: class SouthAfricaCliffSwallow(Bird):
21:
22: #Initialize Cliff Swallow data attributes & obtain Bird inheritance.
23: def __init__(self, sex, flock_size):
24:
25: #Obtain base class data attributes & methods (inheritance)
26: Bird.__init__(self, sex)
27:
28: #Initialize subclass data attributes
29: self.__migratory = 'no' #Non-migratory bird.
30: self.__flock_size = flock_size #How many in flock.
31:
32:
33: #Mutator methods for Cliff Swallow data attributes
34: def set_flock_size(self,flock_size): #No. of birds in sighting
35: self.__flock_size = flock_size
36:
37: #Accessor methods for Cliff Swallow data attributes
38: def get_migratory(self):
39: return self.__migratory
40: def get_flock_size(self):
41: return self.__flock_size
42: pi@raspberrypi ~ $

Remember that modularity is important when you’re creating any program, including Python scripts.
Thus, keeping all the bird subclasses in the same file as the Bird base class is not a good idea.


Putting a Subclass in Its Own Object Module File


For better modularity, you can store a base class in one object module file and store each subclass in
its own module file. In Listing 15.4, you can see the modified /home/pi/py3prog/birds.py
object module file. It does not include the BarnSwallow or SouthAfricanCliffSwallow
subclass.


LISTING 15.4 A Bird Base Class Object File


Click here to view code image


pi@raspberrypi ~ $ cat /home/pi/py3prog/birds.py
# Bird base class
#
class Bird:
#Initialize Bird class data attributes
def __init__(self, sex):
...
def get_sex(self):
return self.__sex
pi@raspberrypi ~ $
Free download pdf