Skip to main content

Python Operator Overloading

Operator overloading means providing a new meaning of existing operators. normally operator are used to mathematical and comparison operation. But that is not sufficient for a programmer perspectives. so python is opportunity to provide define new meaning of existing operators. know internally class are define the meaning of operators like how to operator are work on specified operands.

look at this example how to operator are work.

print("data">" info")
print("data"+" info")
print("data"==" data")
print(1+2)
Output
True
data info
False
3

This is an basic example to perform multiple string operator. there is following operation are defined by str(Strings class) class. so first check this operation definition.

help(str)
Output
class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
:

 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> str
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
:
:
 |__gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  

::
:
:

look at view this output, that are defined operator definition that will be works of in a our program.

Before viewing examples of operator overloading, first view some situations to required operator overloading. for example.

class Myclass:
  def __init__(self,data):
      self.data=data
  def display(self):
    print(self.data)

obj1=Myclass(6)
obj2=Myclass(4)
obj1.display()
obj2.display()
print(obj1>obj2) #error
Result
6
4
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print(obj1>obj2)
TypeError: unorderable types: Myclass() > Myclass()

In this example we are not given definition of (obj1>obj2). so it will produce an error. because there is an user defined class object so that is programmer is responsible to define the meaning of (obj1>obj2). then define its meaning before its use. so view solution of this problem.

class Myclass:
  def __init__(self,data):
      self.data=data
  def display(self):
    print(self.data)
  def __gt__(self,another) :
    #define our statements
    if(self.data>another.data):
      return True
    else:
      return False

obj1=Myclass(6)
obj2=Myclass(4)
obj1.display()
obj2.display()
print(obj1>obj2) #True
print(obj2>obj1) #False
Output
6
4
True
False
Python greater than operat oroverload

In this example __get__()function is overwrite existing properties of Greater than operator. similar why we can befine other operator defination.

Operators and methods

Operator Name Methods
+ Addition( plus sign) __add__(self,obj)
- Subtract (minus sign) __sub__(self,obj)
/ Divide __truediv__(self,obj)
* multiplication (* symbol) __mul__(self,obj)
% remainder operator __mod__(self,obj)
** Exponent __pow__(self,obj)
// Floor division __floordiv__(self,obj)
> Greater than __gt__(self,obj)
< Less than __lt__(self,obj)
>= Greater than equal to __ge__(self,obj)
<= Less than equal to __ge__(self,obj)
!= Not equal to __ne__(self,obj)
== Equal to equal to __ne__(self,obj)
+= Add and assign __iadd__(self,obj)
-= Subtracts and assign __isub__(self,obj)
*= Multiplies and assign __imul__(self,obj)
/= Divides and assign __idiv__(self,obj)
%= Modulus and assign __imod__(self,obj)
**= power and assign __ipow__(self,obj)
//= Floor Division and assign __ifloordiv__(self,obj)
and (&) Bitwise AND __and__(self,obj)
or (|) Bitwise or __or__(self,obj)
(^) Bitwise Xor __and__(self,obj)
(~) Bitwise Not __invert__(self)

let view few examples in python operator overloading.

Overload arithmetic operator (+,-,*,/,%)

class Myoperator:
  def __init__(self,data):
      self.data=data

  def __add__(self,another) :
    #define our statements
    return self.data+another.data
  
  def __sub__(self,another) :
    #define statements
    return self.data-another.data
  
  def __truediv__(self,another) :
    #define statements
    return self.data/another.data
  
  def __mul__(self,another) :
    #define statements
    return self.data*another.data
  def __mod__(self,another) :
    #define statements
    return self.data%another.data
obj1=Myoperator(6)
obj2=Myoperator(3)
print(obj1+obj2)
print(obj1-obj2)
print(obj1/obj2) 
print(obj1*obj2) 
print(obj1%obj2)  

#same as
print("Similar to") 
print(obj1.__add__(obj2))
print(obj1.__sub__(obj2))
print(obj1.__truediv__(obj2))
print(obj1.__mul__(obj2))
print(obj1.__mod__(obj2))
Output
9
3
2.0
18
0
Similar to
9
3
2.0
18
0
Overload arithmetic operator

In this example when obj1+obj2 is execute __add__() method. there is similar to obj1.__add__(obj2) here obj1 is represent self object and obj2 is represent another object.

Assignment operator overload

#Assignment operator overload
class Assignment:
    def __init__(self,value):
        self.value=value
    def __iadd__(self,other):
        self.value+=other.value
        return self
    def __isub__(self,other):
        self.value-=other.value
        return self
    def __imul__(self,other):
        self.value*=other.value
        return self
    #itruediv for python3
    #__idiv__ for python2    
    def __itruediv__(self,other):
        self.value/=other.value
        return self
    def __imod__(self,other):
        self.value%=other.value
        return self

                      
def main():

   obj1=Assignment(2)
   obj2=Assignment(3)
   print("Before Add and assign :",obj1.value,obj2.value)
   obj1+=obj2
   print("After  Add and assign :",obj1.value,obj2.value)


   obj3=Assignment(6)
   obj4=Assignment(4)
   print("Before Subtracts and assign",obj3.value,obj4.value)
   obj3-=obj4
   print("After  Subtracts and assign",obj3.value,obj4.value)


   obj5=Assignment(4)
   obj6=Assignment(5)
   print("Before Multiplies and assign",obj5.value,obj6.value)
   obj5*=obj6
   print("After  Multiplies and assign",obj5.value,obj6.value)


   obj7=Assignment(10)
   obj8=Assignment(4)
   print("Before Divides and assign :",obj7.value,obj8.value)
   obj7/=obj8
   print("After  Divides and assign :",obj7.value,obj8.value)


   obj9=Assignment(6)
   obj10=Assignment(4)
   print("Before Modulus and assign",obj9.value,obj10.value)
   obj9%=obj10
   print("After  Modulus and assign",obj9.value,obj10.value)



if __name__=="__main__":
    main()
Output
Before Add and assign : 2 3
After  Add and assign : 5 3
Before Subtracts and assign 6 4
After  Subtracts and assign 2 4
Before Multiplies and assign 4 5
After  Multiplies and assign 20 5
Before Divides and assign : 10 4
After  Divides and assign : 2.5 4
Before Modulus and assign 6 4
After  Modulus and assign 2 4
Python assignment operator overload




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment