Python Programming – Overloading Relational Operators
The relational operators can also be overloaded as arithmetic and bitwise operators. The Python language provides a list of built-in functions for overloading relational operators. As we know that relational operators are less than (<), less than equal to (<=), greater than (>), greater than equal to (>=), equal to (=), and not equal to (!=). Here in this section, we will demonstrate, how to overload greater than (>) relational operator. The programming illustration for the same is given in Code 12.4.
In this program, we create a class distance with two data members a and b. Another built-in function __gt__() is defined in the class with two arguments self and obj. The__gt__()function is used to overload greater than the operator in Python. We create two objects dl and d2 of the class distance. The values of data members have been initialized through constructor __init__() while creating these two objects. Then, the two objects dl and d2 are compared by using the greater than operator (>), in the same manner in which two simple variables are compared, i.e., dl>d2. Basically, the call dl>d2 expands as dl. gt (d2).
In the definition part, self in the argument list of__gt__() represents the calling object dl and obj in the argument list represents d2. Then, the magnitude of the distance is computed for both of the objects and their result is compared and returned as self. mag>obj. mag. As we know that the result of the relational expression is either true or false. Therefore, the result for this program is returned as true, which can be seen from the output.
Code: 12.4. Illustration of overloading greater than the operator in Python.
|#illustration of relational ‘>’ operator overloading
Alike, greater than operator other relational operators can also be overloaded. The Python built-in functions for relational operators are given in Table 12.3.
|Less than||cl <c2||cl. It (c2)|
|Less than or equal to||cl <== c2||cl.__le__(c2)|
|Equal to||cl == c2||cl.__eq__(c2)|
|Not equal to||cl != c2||cl.__ne__(c2)|
|Greater than||cl> c2||cl.__gt__(c2)|
|Greater than or equal to||cl >= c2||cl.__ge__(c2)|
|Note: cl and c2 are objects.|