Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Overloading Operators in Python
In Python, you can customize how operators work with your custom classes through operator overloading. This is achieved by defining special methods (also called magic methods) in your class that correspond to specific operators.
Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation ?
Example
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)
The output of the above code is ?
Vector (7, 8)
Common Operator Overloading Methods
Here are some commonly used magic methods for operator overloading ?
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other): # +
return Number(self.value + other.value)
def __sub__(self, other): # -
return Number(self.value - other.value)
def __mul__(self, other): # *
return Number(self.value * other.value)
def __eq__(self, other): # ==
return self.value == other.value
def __lt__(self, other): # <
return self.value < other.value
def __str__(self):
return str(self.value)
# Testing the operators
num1 = Number(10)
num2 = Number(5)
print(num1 + num2) # Addition
print(num1 - num2) # Subtraction
print(num1 * num2) # Multiplication
print(num1 == num2) # Equality
print(num1 < num2) # Less than
The output of the above code is ?
15 5 50 False False
Operator Methods Summary
| Operator | Method | Description |
|---|---|---|
| + | __add__ |
Addition |
| - | __sub__ |
Subtraction |
| * | __mul__ |
Multiplication |
| == | __eq__ |
Equality |
| < | __lt__ |
Less than |
| > | __gt__ |
Greater than |
Conclusion
Operator overloading in Python allows you to define custom behavior for operators when used with your classes. By implementing magic methods like __add__, __sub__, and __eq__, you can make your objects work intuitively with Python's built-in operators.
