Overriding Methods in Python

Sometimes you want to override the inherited __init__ function. To demonstrate, we can create a Motorcycle class. Most motorcycles have a center stand. We'll add the ability to either put it out or in on initialization:

class Motorcycle(Vehicle):
    def __init__(self, center_stand_out = False):
        self.center_stand_out = center_stand_out
        super().__init__()

When you override the constructor, the constructor from the parent class (from which we inherited) is not called at all. If you still want that functionality, you have to call it yourself. This is done with super(): it returns a reference to the parent class, so we can call the constructor of the parent class.

In this case, we added functionality for the center stand but removed the option to set the speed and started state in the constructor. If you want, you can add options for speed and started state too and pass those on to the Vehicle constructor.

Overriding other methods

Just like __init__, we can override other methods as well. For example, if you want to implement a motorcycle that doesn't start, you can override the start method:

class Motorcycle(Vehicle):
    def __init__(self, center_stand_out = False):
        self.center_stand_out = center_stand_out
        super().__init__()
    def start(self):
        print("Sorry, out of fuel!")


If you liked this page, please share it with a fellow learner: