Updated October 13, 2023
Introduction to Method Overriding in Python
Method overriding in Python is a fundamental aspect of object-oriented programming that allows a subclass to provide its implementation of a method inherited from its parent class. This will enable developers to customize method behavior for subclasses, improving code flexibility and reusability. By redefining a method in a child class, you can customize its functionality while preserving the overall structure of the parent class. This concept ensures that a subclass can extend or modify the behavior of its parent class, making it a crucial tool for building complex and versatile software systems.
Table of Contents
- Introduction
- Syntax
- Rules and Constraints
- How do I override a method in Python?
- Examples of Method Overriding in Python
Syntax
Below is the syntax:
class parentclass:
def overriding_method(self):
class Childclass:
def overriden_method(self):
object_1 = parent_class()
object_2 = Child_class()
object_1.overriding_method()
object_2.overriden_method()
Rules and Constraints when overriding methods in Python
When you override methods in Python, you must follow specific rules and limitations.:
- Method Signature: The subclass overriding method must match the superclass method’s name, return type, and parameters.
- Inheritance: The subclass must inherit from the superclass containing the method to override.
- Override Keyword: In Python 3, you can use the @override decorator to indicate your intention to override a method. Although it’s not mandatory, it’s good practice.
- Access Level: The overriding method cannot have a more restrictive access level than the method in the superclass. For example, you can’t override a public method with a private one.
- Exceptions: If the overridden method throws checked exceptions, the overriding method should declare the same exceptions or their subtypes. This is more relaxed in Python than in languages with a static type system.
Following these rules ensures that method overriding is done correctly and promotes the fundamental principle of polymorphism in object-oriented programming.
How do I override a method in Python?
To override a method in Python, you can create a subclass that implements a method already defined in its superclass. Follow these steps to override a method correctly:
1. Create a Subclass: First, create a subclass that inherits from the superclass, which contains the method you want to override. This establishes an “is-a” relationship between the subclass and the superclass.
class Superclass:
def method_to_override(self):
# Original method implementation
class Subclass(Superclass):
pass
2. Define the Override Method: In the subclass, define a method with the same name as the one in the superclass that you want to override. Ensure the method signature (name, parameters, and return type) matches the superclasses.
class Subclass(Superclass):
def method_to_override(self):
# New implementation for the overridden method
3. Optional: Use @override Decorator (Recommended): Though not mandatory, it’s a good practice to use the @override decorator to indicate your intention to override the method. This can help catch accidental mistakes in your code.
class Subclass(Superclass):
@override
def method_to_override(self):
# New implementation for the overridden method
4. Customize the Behavior: Inside the overridden method in the subclass, provide the new implementation that customizes the method’s behavior. You can call the superclass’s method using super() to extend the behavior rather than replace it.
class Subclass(Superclass):
@override
def method_to_override(self):
super().method_to_override() # Call the superclass method if needed
# New behavior specific to the subclass
By following these steps, you can successfully override a method in Python. When you call the subclass method, it invokes specialized behavior while still maintaining the class hierarchy.
Examples of Method Overriding in Python
Below are the examples of the method overriding:
Example #1
Code:
class parent_class:
def __init__(self,Lowercase,Uppercase):
self.Lowercase = Lowercase
self.Uppercase = Uppercase
def attribute_determining_method(self):
print('Lower case variable type: ',type(Lowercase))
print('Upper case variable type: ',type(Uppercase))
print('Lower case alphabets: ',len(Lowercase), Lowercase)
print('Upper case alphabets: ',len(Uppercase), Uppercase)
class child_class:
def __init__(self,PrimeNumbers):
self.PrimeNumbers = PrimeNumbers
def attribute_determining_method (self):
print('Collection used for variable3 :',type(PrimeNumbers))
print('Lower case alphabets : ', len(PrimeNumbers),PrimeNumbers)
Lowercase=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Uppercase=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
PrimeNumbers=['1','3','5','7','11','13','17','19','29','31','37','41','43','47','53','59','61','67','71','73','79','83','89','97']
object_A = parent_class(Lowercase,Uppercase)
object_A. attribute_determining_method()
object_B = child_class(PrimeNumbers)
object_B. attribute_determining_method()
Output:
Explanation: The above program employs three lists, two in the middle of the asset, the lower case and the upper case letters; the third one seizes the prime number ideals from 0 to 100. This approach focuses on the program’s flow, which accepts specifications and data to print for the corresponding lists. In this case, two different classes serve this purpose. The parent class levers every compilation of alphabets, while the child class levers the collection for prime numbers.
The function ‘attribute_determining_method()’ is affirmed as a piece of mutual classes. This method grips the characteristic dispensation for the alphabet; for the child class, it grips the characteristic dispensation for prime numbers. The noteworthy condition is that the method name is identical in both affirmed classes.
When an entity is instantiated for the parent class, it can trigger a function call to the function in the parent class. Similarly, for other purposes, the object instantiated for the child class can initiate a function call to the method in the child class. This implies that when you call ‘object_B.attribute_determining_method,’ it invokes the function in the child class, even if there’s an equivalent method in the parent class. This justifies overriding the child class method over the parent class, as it incorporates the detail that the subclass provides a specific type of functionality in which the subclass element overrides the parent class components.
Example #2
Code:
class Individual:
def __init__(self):
self.Enrolled_Name = input( " Enter Name of the Enrolled : " )
self.Enrolled_age = input( " Enter age of the Enrolled : " )
self.Enrolled_gender = input( " Enter gender of the Enrolled : " )
def display(self):
print( " \n \n Enter Name of the Enrolled : " , self.Enrolled_Name )
print( " Enter age of the Enrolled : " , self.Enrolled_age )
print( " Enter gender of the Enrolled : " , self.Enrolled_gender )
class Estimated_Marks:
def __init__(self):
self.stuClass = input( " Class of the Enrolled : " )
print( " Estimated Marks per subject : " )
self.Science = int(input( " Mark in Science: " ))
self.maths = int(input( " Mark in Math: " ))
self.history = int(input( " Mark in history: " ))
self.hindhi = int(input( " Mark in Hindi: " ))
def display(self):
print( " Study in : " ,self.stuClass)
print( " Total Estimated_Marks : " , self. Science + self.maths + self.history+ self.hindhi)
class Enrolled(Individual, Estimated_Marks):
def __init__(self):
Individual.__init__(self)
Estimated_Marks.__init__(self)
def result(self):
Individual.display(self)
Estimated_Marks.display(self)
Enrolled_1 = Enrolled()
Enrolled_2 = Enrolled()
print("")
print( " Note : The instances get initialized with the given value successfully " )
Output:
Explanation: This program provides another representation of the method overriding flow, explaining how the method’ display()’ gets overridden by both the parent and the child classes. The program follows a pseudo flow to collect user inputs and conclude the process. During the input retrieval process, two distinct objects encounter the ‘Enrolled’ class, and notably, the ‘result()’ method of the ‘Enrolled’ class is instantiated immediately after the ‘init’ constructor method. The ‘result()’ method inherits the ‘display()’ method from its parent class. In the parent class, ‘Estimated marks’ use these marks to calculate the sum of all marks entered for the different subjects associated with each student. This display method is overriden() by the parent methods. It nicely displays the sum onto the corresponding console output. So, the overriding process is achieved when the display method is already part of the super parent class individual. Yet, it could get overridden in the class estimated marks. This precisely depicts the capability of this method getting overridden in different instances.
Conclusion
Method overriding in Python is a powerful feature of object-oriented programming that allows you to customize the behavior of inherited methods in a subclass. Following the rules and constraints can create more specialized and extensible code, promoting code reusability and modularity. Method overriding is a key component of polymorphism, enhancing the flexibility and maintainability of your Python applications.
FAQs
Q1. What happens if I don’t override a method correctly?
Ans: If you don’t follow the method signature (name, parameters, return type), Python won’t recognize it as an override, and this can cause unexpected behavior in the code.
Q2. What is the distinction between method overloading and method overriding?
Ans: Method overloading involves defining multiple methods with the same name but different parameters in a class. Method overriding, on the other hand, consists of providing a specific implementation of a method from the superclass in a subclass.
Q3. What’s the role of the super() function in method overriding?
Ans: The super() function calls a method from the superclass within the overriding method. It’s helpful when you want to extend the behavior of the superclass method while maintaining its functionality.
Recommended Articles
We hope this EDUCBA information on “Method Overriding in Python” benefited you. You can view EDUCBA’s recommended articles for more information.