Python - Operator Overloading

Python - Operator Overloading


Previous Page

With operator overloading feature in Python, we can make operators to work for user defined classes. As we create a class, it creates a new type in the code and Python allows us to specify the operators with a special meaning for a data type, this ability is known as operator overloading. For example - '+' operator can be overloaded for a string class to concatenate two strings.

Overloaded operators are function with special name. The name starts with keyword operator followed by operator symbol. Like any other function, the overloaded operator has return type and passing arguments. Mostly, operator overloading is achieved by non-member functions or class member functions.

In the below case, operator overloading is done by class member function. The return type of the function is Vector and it requires one argument (a Vector object) to pass.

Vector operator+ (const Vector& v)

The below case describes operator overloading using non-member function. The return type of the function is Vector and it requires two argument (two Vector objects) to pass.

Vector operator+ (const Vector& v1, const Vector& v2)

Example:

The below examples describes, how to overload + operator to add two vectors. Here, the vector v1 is taken as (10, 15) and vector v2 ia taken as (5, 25). The addition operation of v1 and v2 creates v3 which is (10+5, 15+25) or (15, 40).

class Vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __str__(self):
    return "({0},{1})".format(self.x, self.y)
  #function for operator overloading
  def __add__(self, other):
    X = self.x + other.x
    Y = self.y + other.y
    return Vector(X, Y)

v1 = Vector(10, 15)
v2 = Vector(5, 25)
v3 = v1 + v2
print("v3 =", v3)

Output

v3 = (15,40) 

Overloadable operators in Python

Following is the list of operators that can be overloaded in Python.

Overloadable operators in Python
+-*/=<>
+=-=*=/===<<>>
++--<<=>>=!=<=>=
%&^!|~&=
^=|=&&||%=()[]
,->*->newdelete new[]delete[]

Non-overloadable operators in Python

Here is the list of operators that can not be overloaded in Python.

Non-overloadable operators in Python
..*::? :###

Operator Overloading Examples

Here is the list of various operator overloading examples which can be used to understand the concept more deeply.

S.N.Operator Overloading Examples
1.

Previous Page