Operator Overloading in Python
In Python, special methods like __add__ are used to define the behavior of operators for user-defined classes. Here’s a simple example to overload + operator with a Complex class for complex numbers:
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
# Overload + operator
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
# Display method
def display(self):
print(f"{self.real} + {self.imag}i")
if __name__ == "__main__":
c1 = Complex(3.0, 4.0)
c2 = Complex(1.0, 2.0)
c3 = c1 + c2 # Using overloaded +
c3.display() # Output: 4.0 + 6.0i
Output
4.0 + 6.0i
Note: Operator Overloading is not supported in C, Java and Javascript.
Operator Overloading in Programming
Operator Overloading is a feature in some programming languages used to redefine or “overload” the standard behavior of operators (such as +, -, *, etc.) to work with user-defined data types. This is useful when working with objects of custom classes. In this article, we will learn about the basics of Operator overloading and its implementation in different languages.
Table of Content
- What is Operator Overloading?
- Operator Overloading in C++
- Operator Overloading in Python
- Advantages of Operator Overloading
- Disadvantages of Operator Overloading