Python Programming – Overloading ‘+’ Operator in Python
Overloading the *+’ operator is quite simpler in Python than in C++. The overloaded + operator can add the values contained in two objects by following the same syntax that is used for adding two simple variables. The programming example to overload the arithmetic ‘+’ operator is given in Code 12.1. In this program, we see that a class complex is created with two member variables real and imag, which are initialized by using the __init__( ) constructor function. Then for overloading the plus “+’ operator the built-in Python function __add_( ) is used. This function is specifically meant for adding two objects, which signifies the concept of operator overloading. The user-defined function display(), displays the values of object variables.
In this program, we create two objects cl and c2 of the class complex with initializing values of data members. Then, the values of class data members are displayed associated with these two objects cl and c2. Subsequently, the addition of two objects cl+c2 is performed by using the same syntax that is used for adding two simple variables. The result of cl+c2 is assigned to a third object c3. Then, the result is displayed by invoking the c3.display( ) function.
When the statement cl+c2 encounters, it expands as c1.__add__(c2), that means the cl object invokes the built-in addition overloading function__add__() with c2 as an argument. After the invocation of this function, the control goes to the definition part of __add__( ) function, where it receives two arguments self and obj. The self-object in the argument represents the calling object in the invocation of the function cl. add (c2), which is cl and obj in the argument represents the c2 object, which is passed as an argument.
The computation of addition has been performed by accessing the class data members as self.real+obj.real. That means the real part of cl (self) is added with the real part of c2 (obj) and the result is assigned to the real and imag data members of the class. A similar operation is performed for adding the imaginary part. After the computation, both the real and imag variables are returned to the calling function cl+c2, which is received by the c3 object. Subsequently, the result is displayed by calling c3.display(). The output of this code presents the intended result.
Code: 12.1. Illustration of overloading ‘+’ operator in Python
|#illustration of arithmetic plus ‘+’ operator overloading