Spex3
    

Polymorphism in Python: Method Overloading 🐍🔄


    

    

Polymorphism allows objects of different classes to be treated as if they were the same type. One way to achieve polymorphism is method overloading, where multiple methods share the same name but have different numbers or types of arguments.

📌 Python does NOT support traditional method overloading (like Java or C++).
📌 Instead, Python handles method overloading dynamically using default arguments, *args, or **kwargs.

1️⃣ Traditional Method Overloading (Not Supported in Python)
In languages like Java or C++, method overloading means defining multiple methods with the same name but different parameters.

🚫 Not Possible in Python

class MathOperations:
def add(self, a, b):
return a + b

def add(self, a, b, c): # ❌ Overwrites the previous method
return a + b + c

math_op = MathOperations()
# print(math_op.add(2, 3)) ❌ Error (Only last method is considered)
🔹 Python does not allow multiple methods with the same name in a class.
🔹 The last-defined method (add(a, b, c)) overwrites the first one.

2️⃣ Python's Approach to Method Overloading
Python uses default arguments, *args, and **kwargs to achieve similar functionality.

✅ Using Default Arguments

class MathOperations:
def add(self, a, b, c=0): # Default value for c
return a + b + c

math_op = MathOperations()
print(math_op.add(2, 3)) # ✅ Calls add(a, b)
print(math_op.add(2, 3, 4)) # ✅ Calls add(a, b, c)
🔹 The c=0 default parameter makes it optional, mimicking method overloading.

✅ Using *args (Variable-Length Arguments)

class MathOperations:
def add(self, *numbers): # Accepts any number of arguments
return sum(numbers)

math_op = MathOperations()
print(math_op.add(2, 3)) # ✅ Works for two arguments
print(math_op.add(2, 3, 4, 5)) # ✅ Works for multiple arguments
🔹 *args allows passing any number of arguments, making it flexible.

✅ Using @classmethod for Alternative Constructors

class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age

@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2025 - birth_year) # Calculates age

p1 = Person("Alice", 30)
p2 = Person.from_birth_year("Bob", 1995) # Uses alternative constructor

print(p1.name, p1.age) # Alice, 30
print(p2.name, p2.age) # Bob, 30
🔹 The from_birth_year() acts like an overloaded constructor.

3️⃣ Summary Table

Approach Description Example
Default Arguments Provides default values for missing parameters def add(self, a, b, c=0)
*args (Variable-Length Arguments) Allows passing multiple arguments def add(self, *numbers): return sum(numbers)
@classmethod for Alternative Constructors Defines multiple ways to create an object from_birth_year()
4️⃣ When to Use Python's Overloading Techniques?

✅ When you need flexible method signatures (different arguments).

✅ When you want to avoid writing multiple methods with similar logic.

✅ When you need alternative constructors for object creation.


    Date: 2025-03-24 00:00:00.000000