Function Overloading in Python

 

Function Overloading in Python

In many languages like C++ or Java, function overloading allows multiple functions with the same name but different parameters (type or number). But Python does not support traditional function overloading.

Instead, Python uses default arguments, variable arguments (*args, **kwargs), and type checking inside functions to achieve similar behavior.

Simulating Function Overloading in Python

✅ 1. Using Default Arguments:


def greet(name="Guest"): print(f"Hello, {name}!") greet("Alice") # Output: Hello, Alice! greet() # Output: Hello, Guest!

Here, the same function works with or without an argument.


✅ 2. Using *args (Variable number of arguments):


def add(*numbers): total = 0 for n in numbers: total += n print(f"Sum: {total}") add(2, 3) # Output: Sum: 5 add(1, 2, 3, 4, 5) # Output: Sum: 15

✅ 3. Using type checking inside the function:


def area(a, b=None): if b is None: print(f"Area of square: {a * a}") else: print(f"Area of rectangle: {a * b}") area(5) # Output: Area of square: 25 area(5, 10) # Output: Area of rectangle: 50

Comments

Popular posts from this blog

Python For Application Development MNCST 309 KTU BTech CS Minor 2024 Scheme - Dr Binu V P

Course Details MNCST 309 Python For Application Development

Regular Expression