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

(singke) #1
flock_size—Indicates the number of birds seen in one sighting.

(Remember that this is an overly simplified example. A real barn swallow would have many more
data attributes.)


These specialized data attributes are set using the following Python statements.


Click here to view code image


self.__migratory = 'yes'
self.__flock_size = flock_size

Since the first data attribute for the BarnSwallow subclass is immutable, the only mutator method
needed is for flock_size. This is set as follows:


Click here to view code image


def set_flock_size(self,flock_size):
self.__flock_size = flock_size

Finally, in the BarnSwallow subclass object definition, the accessor methods must be declared for
the subclass data attributes. They are shown here:


Click here to view code image


def get_migratory(self):
return self.__migratory
def get_flock_size(self, flock_size):
return self.__flock_size

Once all the parts of the object definition have been determined, you can add the subclass to an object
module file.


Adding a Subclass to an Object Module File


The BarnSwallow subclass object definition can be stored in the same module file as the Bird
base class (see Listing 15.2).


LISTING 15.2 The BarnSwallow 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: # Barn Swallow subclass (base class: Bird)
10: #
11: class BarnSwallow(Bird):
12:
13: #Initialize Barn Swallow data attributes & obtain Bird inheritance.
14: def __init__(self, sex, flock_size):
15:
16: #Obtain base class data attributes & methods (inheritance)
17: Bird.__init__(self, sex)
18:
Free download pdf