Overloading
Overloading allows the same method name or operator to behave differently depending on the number or type of arguments involved, letting your code adapt naturally to different situations.
Method Overloading in Python
Unlike some languages, Python does not support traditional method overloading (defining multiple methods with the same name but different parameters). Instead, the same result is achieved using default arguments or *args.
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
calc = Calculator()
print(calc.add(5)) # 5
print(calc.add(5, 10)) # 15
print(calc.add(5, 10, 15)) # 30
Operator Overloading
Operator overloading lets you define how built-in operators like +, -, and == behave when used with objects of your own custom class, using special "dunder" (double underscore) methods.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2) # Point(4, 6)
Here, defining __add__ teaches Python exactly what the + operator should do when used between two Point objects.
__add__ (+), __sub__ (-), __eq__ (==), __lt__ (<), and __len__ (len()).Coming Up Next
Next, you'll learn about Overriding - how a child class can redefine a method it inherits from its parent class.