Method Overloading vs Method Overriding

Method overloading

  • Method overloading refers to defining multiple methods with the same name but different parameters (e.g., different numbers or types of arguments) within the same class .
class Example:
    def display(self, a=None, b=None):
        if a is not None and b is not None:
            print(f"Two arguments: {a}, {b}")
        elif a is not None:
            print(f"One argument: {a}")
        else:
            print("No arguments")

# Usage
obj = Example()
obj.display()          # Output: No arguments
obj.display(10)        # Output: One argument: 10
obj.display(10, 20)    # Output: Two arguments: 10, 20

Method overriding

  • Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its parent class.

  • The method in the subclass has the same name and same signature (parameters) as the method in the parent class.

class Parent:
    def greet(self):
        print("Hello from Parent!")

class Child(Parent):
    def greet(self):  # Overrides the greet method from Parent
        print("Hello from Child!")

# Usage
parent = Parent()
child = Child()

parent.greet()  # Output: Hello from Parent!
child.greet()   # Output: Hello from Child!

Why Does Python Handle These Differently?

  • Method Overloading: Python doesn’t need true method overloading because it allows functions to accept any number or type of arguments dynamically. Instead, you can use techniques like default arguments or variable-length arguments to achieve similar behavior.

  • Method Overriding: Python fully supports method overriding because it’s a fundamental feature of object-oriented programming. It enables polymorphism, allowing subclasses to customize behavior while maintaining a consistent interface.

Final Takeaway

  • Method Overloading: Defines multiple methods with the same name but different parameters in the same class . Python simulates this using default arguments or variable-length arguments.

  • Method Overriding: A subclass provides a specific implementation of a method already defined in its parent class , with the same name and parameters. Python fully supports this.

Updated on