Chapter 2: Inheritance

Method overriding

face Josiah Wang

Back to our RPG example! Let us now implement the Monster class. 👾

Inheritance example

Remember that Enemy has an evil_laugh() method that prints out Hehehehehe!

Monster will naturally inherit this method. But Monster actually laughs quite differently from its Enemy superclass. So we need to let it have its own evil laughter rather than following the Enemy laughter! 👾👾👾

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Monster(Enemy):
    def __init__(self, name, health=50, strength=30, defence=20, evilness=50,
                 smelliness=100):
        super().__init__(name, health, strength, defence, evilness)
        self.smelliness = smelliness

    def evil_laugh(self):
        print("WAHAHAHAHAHAHAHAHAHA!!! HA!!")


monster = Monster("Bigfoot", 100, 70, 40, 50, 1000)
monster.evil_laugh()

If you run the code above (you will also need Character and Enemy), you will find that the monster now has its own customised evil laugh. WAHAHAHAHAHAHAHAHAHA!!! HA!!

This is called method overriding. You basically replace the superclass’ method with your own.

Accessing a superclass’ method

Say you now need Monster to first laugh like an Enemy and then add its own custom laugh to it (because all Enemy must start by laughing that way!)

Use super() to access the superclass Enemy’s version of evil_laugh() (Line 8).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Monster(Enemy):
    def __init__(self, name, health=50, strength=30, defence=20, evilness=50, 
                 smelliness=100):
        super().__init__(name, health, strength, defence, evilness)
        self.smelliness = smelliness

    def evil_laugh(self):
        super().evil_laugh()
        print("WAHAHAHAHAHAHAHAHAHA!!! HA!!")


monster = Monster("Bigfoot", 100, 70, 40, 50, 1000)
monster.evil_laugh()

Your output should now say:

Hehehehehe!
WAHAHAHAHAHAHAHAHAHA!!! HA!!