Write a python program to implement Method Overloading.

 Write a python program to implement Method Overloading.


1. Using Default Arguments

class Calculator:

    # Simulates overloading the 'add' method for 2 or 3 arguments

    def add(self, a, b, c=None):

        if c is None:

            return a + b

        else:

            return a + b + c


calc = Calculator()

print(f"Adding two numbers: {calc.add(10, 20)}")

print(f"Adding three numbers: {calc.add(10, 20, 30)}")






2. Using Variable Arguments (*args)

class Calculator:

    # Accepts any number of arguments

    def add(self, *args):

        return sum(args)


calc = Calculator()

print(f"Sum of two numbers: {calc.add(5, 10)}")

print(f"Sum of multiple numbers: {calc.add(5, 10, 20, 30)}")




Comments