Class inheritance

Inheritance is a property that allows a class to build on another class by inheriting the variables and methods (functions) from the parent class. The prevents replicating code which would cause added complexity any time the code required testing or changing.

You can use the super() function to access the functions of the parent function. This means that your __init__() function only needs to update the new variables in the child class and then just pass the other ones to the parent class’s __init__() function.

class TestClass(object):
    def __init__(self, first_var, second_var):
        self.x = first_var
        self.y = second_var

class AnotherClass(TestClass):
    def __init__(self, a, b, x, y):
        self.a = a
        self.b = b
        super().__init__(x, y)

test_variable = TestClass(30, 60)
print(test_variable.x)

another_test_variable = AnotherClass(100, 200, 500, 600)
print(another_test_variable.x)
print(another_test_variable.a)

Here we can see the AnotherClass class inherits the TestClass as a parent. How do we see this? Look at the class definition line. Instead of having object in the brackets it has TestClass. The object just meant it was inheriting the default Python class, whereas TestClass means it is inheriting the TestClass as its parent. And because TestClass inherits the default class then AnotherClass also gets those. The child class gets everything the parent class has.

In the AnotherClass __init__() function we can see that it only overrides the a and b variables. It just passes x and y into the super().__init__() function. In other words it calls the parent class’s __init__() function and sends it the values that it needs.

Example

Let’s alter our game weapon example.

class Weapon(object):
    def __init__(self, name, damage_type, damage, speed):
        self.name = name
        self.damage_type = damage_type
        self.damage = damage
        self.speed = speed

short_sword = Weapon("Short Sword", "Piercing", 5, 10)
battle_axe = Weapon("Battle Axe", "Slashing", 20, 3)

print(short_sword.name,"does",short_sword.damage,"damage")

class MagicWeapon(Weapon):
    def __init__(self, name, damage_type, damage, speed, effect):
        super().__init__(name, damage_type, damage, speed)
        self.effect = effect

magic_spear = MagicWeapon("Magic Spear", "Piercing", 25, 7, "Fire")
print(magic_spear.name, "has a magical", magic_spear.effect, "effect")

Running this would give an output of:

Short Sword does 5 damage
Magic Spear has a magical Fire effect

The original Weapon class remains untouched and therefore will not break any code that refers to it.

Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.