The Wayback Machine - https://web.archive.org/web/20241126030343/https://www.geeksforgeeks.org/method-overriding-in-python/
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


Previous Article
Next Article

Similar Reads

Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Overriding toString() method in Scala
Consider the following Scala program: // Scala Program without override toString method // Creating Class class Language(LangArticle: Int, LangName: String) { // Defining getLangArticle method def getLangArticle() : Int = { return LangArticle; } // Defining getLangName method def getLangName() : String = { return LangName; } } // Creating object ob
2 min read
Ruby | Method overriding
Method is a collection of statements that perform some specific task and return the result. Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, metho
2 min read
Overriding the save method - Django Models
The save method is an inherited method from models.Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some r
3 min read
Overriding Nested Class members in Python
Overriding is an OOP's (object-oriented programming) concept and generally we deal with this concept in Inheritance. 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
2 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Python | os.abort() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.abort() method in Python is used to generate a SIGABRT signal to the current process. On Unix, this method produces a core dump
2 min read
Python | os.renames() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works like os.rename() method except creation of any int
2 min read
Python | os.lseek() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.lseek() method sets the current position of file descriptor fd to the given position pos which is modified by how. Syntax: os.ls
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Python | Sympy Line.is_parallel() method
In Sympy, the function is_parallel() is used to check whether the two linear entities are parallel or not. Syntax: Line.is_parallel(l2) Parameters: l1: LinearEntity l2: LinearEntity Returns: True: if l1 and l2 are parallel, False: otherwise. Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2 = Point(0, 0), Point(1, 1) p
1 min read
Python PIL | GaussianBlur() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter. Syntax: PIL.ImageFilter.GaussianBlur(radius=5) Par
1 min read
Python range() Method
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Syntax : range(start, stop, step)Parameters : start : Element from which sequence const
3 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isprintable() Method
Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 )Uppercase letters ( ABC
3 min read
Python String isnumeric() Method
The isnumeric() method is a built-in method in Python that belongs to the string class. It is used to determine whether the string consists of numeric characters or not. It returns a Boolean value. If all characters in the string are numeric and it is not empty, it returns “True” If all characters in the string are numeric characters, otherwise ret
3 min read
Python | Numpy np.hermefit() method
With the help of np.hermefit() method, we can get the least square fit of hermite series by using np.hermefit() method. Syntax : np.hermefit(x, y, deg) Return : Return the least square fit of given data. Example #1 : In this example we can see that by using np.hermefit() method, we are able to get the least square fit of hermite series by using thi
1 min read
Python | Numpy np.hermevander() method
With the help of np.hermevander() method, we can get the pseudo vandermonde matrix at a given degree by using np.hermevander() method. Syntax : np.hermevander(x, deg) Return : Return the pseudo vandermonde matrix. Example #1 : In this example we can see that by using np.hermevander() method, we are able to get the pseudo vandermonde matrix at a giv
1 min read
Python groupby method to remove all consecutive duplicates
Given a string S, remove all the consecutive duplicates. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.group
2 min read
Python Set clear() Method
Python Set clear() method removes all elements from the set. Python Set clear() Method Syntax: Syntax: set.clear() parameters: The clear() method doesn't take any parameters. Return: None Time complexity : The time complexity of set.clear() function on a set with n element is O(n) . Example 1: Python Set clear() Method Example C/C++ Code test_set =
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg