Method Overriding in Python With Example

Method overriding in Python

Now, we are going to have a quite detailed look at another interesting concept, called the Method overriding. This is a very important feature of inheritance. Let’s consider an example over here so that we can understand the concept of Method overriding in a better way.

Let’s consider that we have an Animal class. It has some behaviors and attributes which are there in most animals, like walking, eating, sleeping, etc. Now, the thing is that there are many different types of animals, like lions, dogs, Sheep, Human (Yes, humans are animals). Now, all these animals also have basic behaviors, like sleeping, eating, walking, running, etc., but they can also have their own implementation for that behaviors. For example, sheep are herbivore, which means that it eats grass, plants, etc…  On the other hand, Lions are Carnivores

Method Overriding in Python

So, the point is that the lion has inherited the behavior of eating from the Animal class, but it has implemented it in its own way. If you feel confused, do not even worry about it, because most of the things should get clear from the example, that we are going to consider now.

From the above example, we can simply know that the Lion class inherits the Animal class, so, it has got the behaviors and/or attributes from the Animal class in this case. Now, the thing is that if we try to create the Lion object, and then try to implement the eat method on the lion object, we do not have any problem, because the eat method is available to the lion object because of the inheritance.

But here, we are now going to redefine the method eat, for the lion, which will have the implementation of the eat method for the lion. Have a look at the below example now –

As you can see, now, in the Lion class as well, we have redefined the method eat, so, we are overriding the method eat here. The concept is called method overriding, and the method is called the overriding method.

You can simply see that the eat method was already provided for the lion class due to inheritance, but we redefined the eat method in the Lion class. So, if we are writing the method in the subclass, with the same name, same parameters, and return types (if applicable) as from the superclass, then we can say that the method in the subclass overrides the method in the superclass.