Operator Overloading in Python with example
The meaning of operators like +, =, *, /, >, <
etc are predefined in any programming language. Programmers can use them directly on built-in data types to write their programs. But, for user-defined types like objects, these operators do not work. Therefore, Python allows programmers to redefine the meaning of operators when they operate on class objects. This feature is called Operator Overloading. It allows programmers to extend the meaning of existing operators so that in addition to the basic data types, they can be also applied to user-defined data types.
Advantages of Operator Overloading:
1. With operator overloading, programmers can use the same notations for user-defined objects and built-in objects.
2. With operator overloading, a similar level of syntactic support is provided to user-defined types as provided to the built-in types.
3. In scientific computing where the computational representation of mathematician objects is required, operator overloading provides great ease to understand the concept.
4. Operator overloading makes the program clearer.
Example:
class Complex: def __init__self(self): self.real=0 self.imag=0 def setValue(self, real, imag): self.real=real self.imag=imag def display(self): print("(", self.real, "+", self.imag, "i)") C1=Complex() C1.setValue(1,2) C2=Complex() C2.setValue(3,4) C3=Complex() C3=C1+C2 C3.display()
Output:
Traceback (most recent call last):
File “C:/Users/Educlick/Documents/complex.py”, line 15, in
C3=C1+C2
TypeError: unsupported operand type(s) for +: ‘Complex’ and ‘Complex’