Chapter 2: Inheritance

Why method overriding?

face Josiah Wang

A practical use of method overriding is that you do not need to know in advance what specific type an object is.

For example, one can use a weapon to hurt a person. One does not need to know whether the weapon is a knife, a sword, a gun, a stick, a wand, a frying pan, or a nunchaku. As long as it is a weapon, one can use it to hurt someone! One also does not care how the weapon hurts someone, as long as it can do it!

The following example shows how this might work. No animals or humans were actually hurt in the process! Study the code below.

  • Notice how each person has a different weapon (Lines 37-39).
  • Also notice how each weapon hurts the victim differently (Lines 10-20).
  • Note that Grandma Edna attacks a dog (Line 40), while the other two attack a person (Line 41-42). We did not add any special code to deal with this - they simply attack the animal, whether it’s a person or a dog!
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Animal:
    def __init__(self, name):
        self.name = name


class Weapon:
    def hurt(self, animal):
        print(f"Used weapon on {animal.name}")

class Knife(Weapon):
    def hurt(self, animal):
        print(f"{animal.name} is cut.")

class Gun(Weapon):
    def hurt(self, animal):
        print(f"{animal.name} is shot.")

class Stick(Weapon):
    def hurt(self, animal):
        print(f"{animal.name} is hit.")


class Dog(Animal):
    pass

class Person(Animal):
    def __init__(self, name, weapon):
        super().__init__(name)
        self.weapon = weapon

    def attack(self, animal):
        print(f"{self.name} attacks {animal.name}")
        self.weapon.hurt(animal)


dog = Dog(name="Bobby")
lady = Person(name="Grandma Edna", weapon=Stick())
mugger = Person(name="Frank the Mugger", weapon=Knife())
mafia_boss = Person(name="The Boss", weapon=Gun())
lady.attack(dog)
mugger.attack(lady)
mafia_boss.attack(mugger)

If you copy and run the above code, the output will be:

Grandma Edna attacks Bobby
Bobby is hit.
Frank the mugger attacks Grandma Edna
Grandma Edna is cut.
The Boss attacks Frank the mugger
Frank the mugger is shot.

As you can see, a Person can use its weapon to hurt any animal (Line 33), whatever the weapon is. Depending on what weapon it is (Line 29), it will hurt the animal differently.

Similarly, it does not matter whether the animal victim is a person, a dog or a duck. A weapon can be used to hurt the animal.

Hopefully you can see the power of inheritance in action!