Python Operator Overloading And Magic Methods

In this article, you will learn about Python operator overloading in which depending on the operands we can change the meaning of the operator. You will also learn about the magic methods or special functions in Python.

Operator overloading in Python
Example: Overloading + operator in Python
Python magic methods or special functions
Example: Overloading assignment operator +=
Example: Overloading comparison operator >

python operator overloading

Operator Overloading In Python

Basically, operator overloading means giving extended meaning beyond their predefined operational meaning.

For example, a + operator is used to add the numeric values as well as to concatenate the strings. That’s because + is overloaded for int class and str class. But we can give extra meaning to this + operator and use it with our own defined class. This method of giving extra meaning to the operators is called operator overloading.

How to overload the operators in Python?

There is an underlying mechanism related to operators in Python.

The thing is when we use operators, a special function or magic function is automatically invoked that is associated with that particular operator.

For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. So by changing this magic method’s code, we can give extra meaning to the + operator.

Just like __add__ is automatically invoked while using + operator, there are many such special methods for each operator in Python.

Overloading + operator in Python

class Example:
  """ Program to overload + """
  def __init__ (self, a , b)
     self.a = a
     self.b = b
  
  def __add__(self,other):
     return Example(self.a + other.a, self.b + other.b)

obj1 = Example(1,2)
obj2 = Example(3,4)
obj3 = Example(1.2,2.2)
print (obj1 + obj2)
print (obj1 + obj3)

[adsense1]

As you can see in above example, we have overloaded + operator to add two objects by defining __add__ magic method and when we run the program it will generate following output.

<__main__.Example object at 0x03696910>

That didn’t go as we expected. So, what we can do is to modify another magic method __str__ to produce the result as we desire.

Here is how we do it.

class Example:
  """ Program to overload + """
  def __init__ (self, a , b):
     self.a = a
     self.b = b
  
  def __add__(self,other):
     return Example(self.a + other.a, self.b + other.b)

  def __str__(self):
 return "({0},{1})".format(self.a,self.b)

obj1 = Example(1,2)
obj2 = Example(3,4)
obj3 = Example(1.2,2.2)
print (obj1 + obj2)
print (obj1 + obj3)

Output

Now this will generate following output.

(4,6)
(2.2,3.2)

Python Magic Methods Or Special Functions

As we already there are tons of Special functions or magic methods in Python associated with each operator. Here is the tabular list of Python magic methods.

List of Assignment operators and associated magic methods.

Assignment Operators Magic Method or Special Function
-= object.__isub__(self, other)
+= object.__iadd__(self, other)
*= object.__imul__(self, other)
/= object.__idiv__(self, other)
//= object.__ifloordiv__(self, other)
%= object.__imod__(self, other)
**= object.__ipow__(self, other)
>>= object.__irshift__(self, other)
<<= object.__ilshift__(self, other)
&= object.__iand__(self, other)
|= object.__ior__(self, other)
^= object.__ixor__(self, other)

List of Comparison operators and associated magic methods.

Comparison Operators Magic Method or Special Function
< object.__lt__(self, other)
> object.__gt__(self, other)
<= object.__le__(self, other)
>= object.__ge__(self, other)
== object.__eq__(self, other)
!= object.__ne__(self, other)

List of Binary operators and associated magic methods.

Binary Operators Magic Method or Special Function
object.__sub__(self, other)
+ object.__add__(self, other)
* object.__mul__(self, other)
/ object.__truediv__(self, other)
// object.__floordiv__(self, other)
% object.__mod__(self, other)
** object.__pow__(self, other)
>> object.__rshift__(self, other)
<< object.__lshift__(self, other)
& object.__and__(self, other)
| object.__or__(self, other)
^ object.__xor__(self, other)

List of Unary operators and associated magic methods.

Unary Operators Magic Method or Special Function
object.__neg__(self)
+ object.__pos__(self)
~ object.__invert__(self)

Example: Overloading extended assignment operator (+=) in Python

class Example:
    def __init__(self,a,b):
        self.a = a
        self.b = b
 
    def __str__(self):
        return "({0},{1})".format(self.a,self.b)
 
    def __iadd__(self,other):
        self.a += other.a
        self.b += other.b
        return Example(self.a,self.b)

obj1 = Example(1,2)
obj2 = Example(2,3)
obj2 += obj1
print (obj2)

Output

(3,5)

Example: Overloading comparison(>) operator in Python

class Example:
 def __init__(self,a):
   self.a = a
 
 def __gt__(self,other):
   return self.a > other.a

obj1 = Example(1)
obj2 = Example(2)
print (obj2 > obj1)

Output

True