![]() |
VOOZH | about |
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
Prerequisite: Inheritance in Python
👁 overriding-in-pythonThe version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
Example:
super().__init__(): This ensures that the parent class's constructor is called, initializing any attributes defined in the parent class. It’s good practice to call the parent class constructor if it does important initialization.Child class overrides the show() method of the Parent class, so when show() is called on an instance of Child, it uses the Child class’s implementation.Output:
Inside Parent
Inside Child
Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.
Example: Let's consider an example where we want to override a method of one parent class only.
Output:
Inside Child
Inside Parent2
Multilevel Inheritance: When we have a child and grandchild relationship.
Example: Let's consider an example where we want to override only one method of one of its parent classes.
Output:
Inside GrandChild
Inside Parent
Parent class methods can also be called within the overridden methods. This can generally be achieved by two ways.
Using Classname: Parent's class methods can be called by using the Parent classname.method inside the overridden method.
Example:
Output:
Inside Parent
Inside Child
Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by ‘super’.
Example 1:
Output:
Inside Parent
Inside Child
Example 2:
Output:
HEY !!!!!! GfG I am initialised(Class GEG3)
HEY !!!!!! GfG I am initialised(Class GEG2)
HEY !!!!!! GfG I am initialised(Class GEG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12