Operator overloading in Python allows a single operator to perform multiple operations based on the operands’ type. This feature enhances the readability and intuitiveness of code, especially when working with custom classes.
Operator overloading enables us to define custom behavior for standard Python operators like +
, -
, and *
. For instance, the +
operator can add numbers, concatenate strings, or merge lists. This flexibility is achieved because Python internally maps operators to special methods (also known as magic methods).
For example:
5 + 3
performs numeric addition.'Hello' + ' World'
concatenates two strings.[1, 2] + [3, 4]
merges two lists.You can further extend this behavior by defining or overriding these magic methods in your custom classes. This process is known as operator overloading.
Imagine creating a custom class, such as a String
class. By default, the Python compiler doesn’t know how to add a string to an instance of this class. Attempting to do so results in a TypeError
. However, by implementing operator overloading, we can define how the +
operator behaves for our custom class.
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return f'Object: {self.string}'
# Usage
string1 = String('Hello')
print(string1 + ' World')
Output:
TypeError: unsupported operand type(s) for +: 'String' and 'str'
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return f'Object: {self.string}'
def __add__(self, other):
return self.string + other
# Usage
string1 = String('Hello')
print(string1 + ' World')
Output:
Hello World
Python uses special (magic) methods to define the behavior of operators. These methods are recognizable by their double underscores before and after the method name. For example:
__add__
for +
__sub__
for -
__mul__
for *
__eq__
for ==
You can override these methods in your classes to customize the operator’s behavior.
Operator | Special Method |
---|---|
+ | __add__ |
- | __sub__ |
* | __mul__ |
/ | __truediv__ |
// | __floordiv__ |
% | __mod__ |
** | __pow__ |
Operator | Special Method |
---|---|
< | __lt__ |
> | __gt__ |
<= | __le__ |
>= | __ge__ |
== | __eq__ |
!= | __ne__ |
Operator | Special Method |
---|---|
+= | __iadd__ |
-= | __isub__ |
*= | __imul__ |
/= | __itruediv__ |
Operator | Special Method |
---|---|
+ | __pos__ |
- | __neg__ |
~ | __invert__ |
Example: Adding Custom Objects
class Student:
def __init__(self, marks1, marks2):
self.marks1 = marks1
self.marks2 = marks2
def __add__(self, other):
return Student(self.marks1 + other.marks1, self.marks2 + other.marks2)
def __repr__(self):
return f'Student(marks1={self.marks1}, marks2={self.marks2})'
# Usage
s1 = Student(50, 60)
s2 = Student(30, 40)
s3 = s1 + s2
print(s3)
Output:
Student(marks1=80, marks2=100)
Example: Comparing Custom Objects
class Circle:
def __init__(self, radius):
self.radius = radius
def __lt__(self, other):
return self.radius < other.radius
def __eq__(self, other):
return self.radius == other.radius
# Usage
c1 = Circle(5)
c2 = Circle(10)
print(c1 < c2) # True
print(c1 == c2) # False
is
and and
, cannot.Mastering operator overloading in Python allows developers to create powerful and intuitive APIs, making custom classes behave more like built-in types. Whether you’re designing a library or simply enhancing a project, operator overloading can significantly improve your code’s usability and elegance. Click Here to know more our program.