This is an archived version of the course. Please see the latest version of the course.

Inheritance

Like Java, Python supports inheritance. In fact, all classes in Python 3 are subclasses of object by default.

Here is an example of a GameCharacter class and its subclass Enemy.

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
43
44
class GameCharacter:
    def __init__(self, name, health=50, strength=30, defence=20):
        self.name = name
        self.health = health
        self.strength = strength
        self.defence = defence

    def attack(self, victim):
        victim.health = victim.health - self.strength
        print(f"Bam! {self.name} attacked {victim.name}.", 
             f"{victim.name}'s health is now {victim.health}")

    def defend(self, attacker):
        self.health = self.health - attacker.strength * 0.25
        print(f"{self.name} defended against {attacker.name}.",
             f"{self.name}'s health is now {self.health}")

    def __str__(self):
        return (f"{self.name} is a GameCharacter (health: {self.health}, "
                f"strength: {self.strength}, defence: {self.defence})"
               )


class Enemy(GameCharacter):
    def __init__(self, name, health=50, strength=30, defence=20, evilness=50):
        # call the constructor of the superclass
        super().__init__(name, health, strength, defence)
        self.evilness = 50

    def evil_laugh(self):
        print("Heheheheheeeeee!!")    

    def __str__(self):
        return (super().__str__().replace("GameCharacter", "Enemy").replace(")", ",") 
                + f" evilness: {self.evilness})" 
               )

boy = GameCharacter("Boy", 100, 20, 10)
evilman = Enemy("Voldemort", 30, 50, 40, 100)
print(boy)
print(evilman)
evilman.attack(boy)
boy.defend(evilman)
boy.evil_laugh()  # You should get an error here.

Line 24: Enemy is a subclass of GameCharacter.

Line 27: If you override the __init__() constructor, then you will need to explicitly invoke the constructor of the superclass GameCharacter with super().__init__(). Otherwise, Enemy will NOT inherit attributes from the superclass like name, health, strength and defence.

super() refers to the superclass - in this case it is GameCharacter.

Line 34: Similarly, if you override any superclass methods, you can access the superclass’ original methods using super().