|
Exit :
3 GeeksFor 12 GeeksGeeksGeeksGeeks
How to overload operators in Python?
Note that we have two objects that are the physical representation of the class (custom data type) and we have to add two objects with the binary operator "+", this throws an error because the compiler doesn’t know how to add two objects, So we define a method for the operator, and this process is called operator overloading. We can overload all existing operators, but we cannot create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically called when it is associated with that particular operator. For example, when we use the + operator, the magic method __add__
is automatically called, which defines the operation for the + operator.
Python binary + operator overloading:
When we use an operator for user-defined data types, the special function or magic function associated with that operator is automatically called. Changing the behavior of an operator is as simple as changing the behavior of a method or function. You define methods in your class, and the operators behave according to the behavior defined in the methods. When we use the + operator, the magic method __add__
is automatically called, which defines the operation for the + operator. There, by changing the code of this magic method, we can give additional meaning to the + operator.
Code 1:
|
Output:
3 GeeksFor
Code 2:
|
Exit:
(3, 5)
Python comparison operator overloading:
|
Output:
ob2 is greater than ob1
Overloading equality and less than operators:
|
Output:
ob1 is lessthan ob2 Not equal
Python magic methods or special functions for operator overloading
Binary Operators :
Operator | Magic Method |
---|---|
+ | __add __ (self, other) |
- | __sub __ (self, other) |
* | __mul __ (self, other) |
/ | __truediv __ (self, other) |
// | __floordiv __ (self, other) |
% | __mod __ (self, other) |
** | __pow __ (self, other) |
Comparison operators:
Operator | Magic Method |
---|---|
& lt; | __lt __ (self, other) |
" | __gt __ (self , other) |
"= | __le __ (self, other) |
" = | __ge __ (self, other) |
== | __eq __ (self, other) |
! = | __ne __ (self, other) |
Assignment Operators:
Operator | Magic Method > |
---|---|
- = | __isub __ (self, other) |
+ = | __iadd __ (self, other) |
* = | __imul__ (self, other) |
/ = | __idiv __ (self, other) |
// = | __ifloordiv __ (self, other) |
| __imod __ (self, other) |
** = | __ ipow __ (self, other) |
Unary operators:
Operator | Magic Method |
---|---|
- | __neg __ (self, other) |
+ | __pos __ (self, other) |
~ | __invert __ (self, other) |