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

(singke) #1
81: if species == '1':
82: print("Species: \t European/Barn Swallow")
83: print("Flock Size: \t", barn_swallow.get_flock_size())
84: print("Sex: \t\t", barn_swallow.get_sex())
85: else:
86: print("Species: \t South Africa Cliff Swallow")
87: print("Flock Size: \t", sa_cliff_swallow.get_flock_size())
88: print("Sex: \t\t", sa_cliff_swallow.get_sex())
89: #
90: #########################################################
91: #
92: ########## Call the main function #######################
93: main()
94: pi@raspberrypi ~

Notice in lines 84 and 88 of Listing 15.8 that the accessor methods are used to obtain the bird’s sex.
.get_sex is an accessor method set in the Bird base class (refer to Listing 15.1, lines 26 and 27).
Both the subclasses BarnSwallow and SouthAfricaCliffSwallow inherited methods from
Bird. Thus, they are able to access the data by using the inherited .get_sex accessor method.
This is called polymorphism.


Did You Know: Polymorphism
Polymorphism is the ability of subclasses to have methods with the same name as
methods in their base class. This is sometimes called overriding a method. You can
still access each class’s method, by using either base_class.method or
subclass.method.

Listing 15.9 shows Python interpreting script1502.py. When the script is run, the subclasses
inherit data attributes and methods with no problems.


LISTING 15.9 script1502.py Interpreted


Click here to view code image


pi@raspberrypi ~ $ python3 /home/pi/py3prog/script1502.py

The following characteristics are listed
in order to help you determine what swallow
you have sighted.

A barn swallow is a bird that is migratory.
A cliff swallow is a bird that is not migratory.
Which did you see?
European/Barn Swallow - 1
African Cliff Swallow - 2
Type number & press Enter: 1

Approximately, how many did you see? 7

Thank you.
The following data will be forwarded to
the Great Backyard Bird Count.
Free download pdf