Method Overriding in Python

23 Jan, 2020
Prerequisite: Inheritance in Python
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, 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.
The 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:
# Python program to demonstrate # method overriding    # Defining parent classclass Parent():          # Constructor    def __init__(self):        self.value = "Inside Parent"              # Parent's show method    def show(self):        print(self.value)          # Defining child classclass Child(Parent):          # Constructor    def __init__(self):        self.value = "Inside Child"              # Child's show method    def show(self):        print(self.value)                    # Driver's codeobj1 = Parent()obj2 = Child()  obj1.show()obj2.show()
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. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance    # Defining parent class 1class Parent1():              # Parent's show method    def show(self):        print("Inside Parent1")          # Defining Parent class 2class Parent2():              # Parent's show method    def display(self):        print("Inside Parent2")                    # Defining child classclass Child(Parent1, Parent2):              # Child's show method    def show(self):        print("Inside Child")             # Driver's codeobj = Child()  obj.show()obj.display()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. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance     # Python program to demonstrate# overriding in multilevel inheritance     class Parent():             # Parent's show method    def display(self):        print("Inside Parent")        # Inherited or Sub class (Note Parent in bracket) class Child(Parent):             # Child's show method    def show(self):        print("Inside Child")    # Inherited or Sub class (Note Child in bracket) class GrandChild(Child):               # Child's show method    def show(self):        print("Inside GrandChild")             # Driver code g = GrandChild()   g.show()g.display()Output:Inside GrandChild
Inside Parent

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. Below is the implementation.# Python program to demonstrate# overriding in multiple inheritance    # Defining parent class 1class Parent1():              # Parent's show method    def show(self):        print("Inside Parent1")          # Defining Parent class 2class Parent2():              # Parent's show method    def display(self):        print("Inside Parent2")                    # Defining child classclass Child(Parent1, Parent2):              # Child's show method    def show(self):        print("Inside Child")             # Driver's codeobj = Child()  obj.show()obj.display()Output:Inside Child
Inside Parent2

Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.
# Python program to demonstrate# overriding in multiple inheritance    # Defining parent class 1class Parent1():              # Parent's show method    def show(self):        print("Inside Parent1")          # Defining Parent class 2class Parent2():              # Parent's show method    def display(self):        print("Inside Parent2")                    # Defining child classclass Child(Parent1, Parent2):              # Child's show method    def show(self):        print("Inside Child")             # Driver's codeobj = Child()  obj.show()obj.display()
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. Below is the implementation.# Python program to demonstrate# overriding in multilevel inheritance     # Python program to demonstrate# overriding in multilevel inheritance     class Parent():             # Parent's show method    def display(self):        print("Inside Parent")        # Inherited or Sub class (Note Parent in bracket) class Child(Parent):             # Child's show method    def show(self):        print("Inside Child")    # Inherited or Sub class (Note Child in bracket) class GrandChild(Child):               # Child's show method    def show(self):        print("Inside GrandChild")             # Driver code g = GrandChild()   g.show()g.display()Output:Inside GrandChild
Inside Parent

Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.
# Python program to demonstrate# overriding in multilevel inheritance     # Python program to demonstrate# overriding in multilevel inheritance     class Parent():             # Parent's show method    def display(self):        print("Inside Parent")        # Inherited or Sub class (Note Parent in bracket) class Child(Parent):             # Child's show method    def show(self):        print("Inside Child")    # Inherited or Sub class (Note Child in bracket) class GrandChild(Child):               # Child's show method    def show(self):        print("Inside GrandChild")             # Driver code g = GrandChild()   g.show()g.display()
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:# Python program to demonstrate# calling the parent's class method# inside the overridden method    class Parent():          def show(self):        print("Inside Parent")          class Child(Parent):          def show(self):                  # Calling the parent's class        # method        Parent.show(self)        print("Inside Child")          # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child

Example:
# Python program to demonstrate# calling the parent's class method# inside the overridden method    class Parent():          def show(self):        print("Inside Parent")          class Child(Parent):          def show(self):                  # Calling the parent's class        # method        Parent.show(self)        print("Inside Child")          # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child

Using Super(): 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:# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super()    class Parent():          def show(self):        print("Inside Parent")          class Child(Parent):          def show(self):                  # Calling the parent's class        # method        super().show()        print("Inside Child")          # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child
Example 2:# Program to define the use of super() # function in multiple inheritance class GFG1:     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG1)')         def sub_GFG(self, b):         print('Printing from class GFG1:', b)     # class GFG2 inherits the GFG1 class GFG2(GFG1):     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG2)')         super().__init__()         def sub_GFG(self, b):         print('Printing from class GFG2:', b)         super().sub_GFG(b + 1)     # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2):     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG3)')         super().__init__()         def sub_GFG(self, b):         print('Printing from class GFG3:', b)         super().sub_GFG(b + 1)         # main function if __name__ == '__main__':         # created the object gfg     gfg = GFG3()         # calling the function sub_GFG3() from class GHG3     # which inherits both GFG1 and GFG2 classes     gfg.sub_GFG(10)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

Example 1:
# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super()    class Parent():          def show(self):        print("Inside Parent")          class Child(Parent):          def show(self):                  # Calling the parent's class        # method        super().show()        print("Inside Child")          # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child

Example 2:
# Program to define the use of super() # function in multiple inheritance class GFG1:     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG1)')         def sub_GFG(self, b):         print('Printing from class GFG1:', b)     # class GFG2 inherits the GFG1 class GFG2(GFG1):     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG2)')         super().__init__()         def sub_GFG(self, b):         print('Printing from class GFG2:', b)         super().sub_GFG(b + 1)     # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2):     def __init__(self):         print('HEY !!!!!! GfG I am initialised(Class GEG3)')         super().__init__()         def sub_GFG(self, b):         print('Printing from class GFG3:', b)         super().sub_GFG(b + 1)         # main function if __name__ == '__main__':         # created the object gfg     gfg = GFG3()         # calling the function sub_GFG3() from class GHG3     # which inherits both GFG1 and GFG2 classes     gfg.sub_GFG(10)
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

Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python | os.path.join() method