Advanced Lesson 2
Advanced Object-Oriented Programming
Chapter 2: Polymorphism
Polymorphism
We will spend this chapter discussing the next ‘pillar’ of OOP: polymorphism.
Poly means many in Greek, while morphism means form.
So polymorphism means the ability to take various forms.
You have actually already seen this in action when we discussed inheritance back in Core Lesson 10.
Recall that you can override the method of a superclass to provide a different functionality (e.g. a Monster
‘s evil laugh can different from its superclass Enemy
‘s evil laugh; or each weapon can hurt its victim differently). This is an example of polymorphism in action.
Here is another form of polymorphism: remember our example where a Person
can use its weapon to attack any victim, whatever the weapon is. Similarly, it does not matter whether the victim is a person, a cat or a penguin. A weapon can be used to hurt any animal. So the attack
method does not even need to know what specific kinds of weapon or animal are involved!
def attack(self, animal):
self.weapon.hurt(animal)