Method Overloading in Python
What is Method Overloading?
Method overloading allows a class to have multiple methods with the same name but different parameters.
Python does not support traditional method overloading like Java or C++.
However, it can be achieved using default arguments or variable-length arguments (*args
/**kwargs
).
Example 1: Simulate Method Overloading Using Default Arguments
class Greet:
def hello(self, name=None):
if name is not None:
print("Hello, " + name)
else:
print("Hello")
g = Greet()
g.hello()
g.hello("Simran")
Output:
Hello
Hello, Simran
Explanation:
Python chooses the method implementation based on arguments passed at runtime, using logic inside the method.
Example 2: Method Overloading Using *args
class Calculator:
def add(self, *args):
return sum(args)
c = Calculator()
print(c.add(5))
print(c.add(5, 10))
print(c.add(1, 2, 3))
Output:
5
15
6
Explanation:
*args
allows the method to accept a variable number of arguments.- Simulates overloading by handling any number of parameters.
Example 3: Using **kwargs
for Flexible Keyword Arguments
class Person:
def info(self, **details):
for key, value in details.items():
print(f"{key}: {value}")
p = Person()
p.info(name="Dharmendra", age=25)
Output:
name: Dharmendra
age: 25
What Happens If You Define the Same Method Twice?
class Demo:
def show(self):
print("First")
def show(self):
print("Second")
d = Demo()
d.show()
Output:
Second
❗ Reason:
- The second
show()
overrides the first one — only one method with a given name can exist.
Example 3: Method Overloading with @singledispatch
(Advanced)
Python’s functools
module offers a decorator @singledispatch
that allows function overloading based on type (Python 3.4+).
from functools import singledispatch
@singledispatch
def show(data):
print("Unsupported type")
@show.register(int)
def _(data):
print("Integer:", data)
@show.register(str)
def _(data):
print("String:", data)
@show.register(list)
def _(data):
print("List with", len(data), "elements")
show(10)
show("Python")
show([1, 2, 3])
Output:
Integer: 10
String: Python
List with 3 elements
Explanation:
- This mimics type-based overloading, though only for functions, not class methods.
Not Supported: Traditional Overloading
class Test:
def show(self):
print("First")
def show(self, msg):
print("Second: " + msg)
t = Test()
t.show("Hello")
Output:
Second: Hello
Why?
Python uses the latest definition of show()
. The earlier one is overwritten.
Summary
Feature | Python Support | Workaround |
---|---|---|
Traditional Overloading | ❌ No | ✅ Use *args , **kwargs , default parameters |
Method Override | ✅ Yes | In child classes |