Open In App

Method Overriding in Python

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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-python

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:

  • 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.
  • Method Override: The 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.
Python
# Python program to demonstrate 
# Defining parent class 
class Parent(): 
    
    # Constructor 
    def __init__(self): 
        self.value = "Inside Parent"
        
    # Parent's show method 
    def show(self): 
        print(self.value) 
        
# Defining child class 
class Child(Parent): 
    
    # Constructor 
    def __init__(self): 
        super().__init__()  # Call parent constructor
        self.value = "Inside Child"
        
    # Child's show method 
    def show(self): 
        print(self.value) 
        
# Driver's code 
obj1 = Parent() 
obj2 = Child() 

obj1.show()  # Should print "Inside Parent"
obj2.show()  # Should print "Inside Child"

Output:

Inside Parent
Inside Child

Method overriding with multiple and multilevel inheritance

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.

Python
# Python program to demonstrate 
# Defining parent class 1 
class Parent1(): 
        
    # Parent's show method 
    def show(self): 
        print("Inside Parent1") 
        
# Defining Parent class 2 
class Parent2(): 
        
    # Parent's show method 
    def display(self): 
        print("Inside Parent2") 
        
        
# Defining child class 
class Child(Parent1, Parent2): 
        
    # Child's show method 
    def show(self): 
        print("Inside Child") 
    
        
# Driver's code 
obj = 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.

Python
# Python program to demonstrate 
# 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


Calling the Parent’s method within the overridden method

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
# 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 code 
obj = 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
# 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 code 
obj = Child() 
obj.show() 

Output:

Inside Parent
Inside Child

Example 2:


Python
# 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

Method Overriding in Python -FAQs

What is Method Overriding in Python?

Method overriding occurs in Python when a method in a subclass has the same name, parameters, and signature as a method in its parent class. By overriding a method, the subclass can provide a specific implementation of the method that is different from the one in its parent class.

Example of Method Overriding:

class Parent:
def show(self):
print("Inside Parent")

class Child(Parent):
def show(self):
print("Inside Child")

# Using the classes
child = Child()
child.show() # Output: Inside Child

Here, the show method in the Child class overrides the one in the Parent class.

What is Method Overloading in Python?

Method overloading refers to the ability to have multiple methods with the same name but different parameters within the same class. Python does not support method overloading by default. However, we can achieve method overloading-like behavior by providing default values for parameters or by using variable-length arguments.

Example Simulating Method Overloading:

class Example:
def display(self, a=None, b=None):
if a is not None and b is not None:
print(a + b)
elif a is not None:
print(a)
else:
print("Nothing to display")

obj = Example()
obj.display()
obj.display(10)
obj.display(10, 20)

What is the Difference Between Overloading and Overriding?

  • Method Overloading is when multiple methods have the same name but different parameters within the same class (not typically supported directly in Python).
  • Method Overriding happens when a subclass redefines a method from its parent class with the same signature to provide a specific implementation.

How Can You Prevent Method Overriding in Python?

Python does not provide built-in support for preventing method overriding, but you can achieve this behavior by convention or using a more complex design pattern, such as using decorators to check if a method in a base class is being overridden in a subclass.

Example Using a Decorator to Discourage Overriding:

def final_method(method):
method.is_final = True
return method

class Parent:
@final_method
def show(self):
print("This method should not be overridden")

class Child(Parent):
def show(self):
print("Trying to override")

# Check if overriding is attempted
if 'is_final' in getattr(Parent().show, '__dict__', {}):
raise TypeError("Method overriding has been prohibited for this method")

child = Child()
child.show() # This will raise an error before execution if checked properly

What is Encapsulation in Python?

Encapsulation in Python refers to the bundling of data with the methods that operate on that data. It restricts direct access to some of the object’s components, which can prevent the accidental modification of data. In Python, encapsulation is typically achieved by prefixing names of attributes or methods with a single underscore (weakly private) or double underscore (strongly private) to suggest or enforce that they are meant to be private.

Example of Encapsulation:

class Computer:
def __init__(self):
self.__max_price = 900 # Private attribute

def sell(self):
print(f"Selling Price: {self.__max_price}")

def set_max_price(self, price):
self.__max_price = price

c = Computer()
c.sell()

# Trying to directly access a private variable
# print(c.__max_price) # This will raise an AttributeError

# Using a method to modify a private variable
c.set_max_price(1000)
c.sell() # Output: Selling Price: 1000


Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg
  翻译: