You can change the meaning of an operator in Python depending upon the operands used. This practice is known as operator overloading.
Python operators work for built-in classes. But same operator behaves differently with different types.
For example, the
+ operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings.
This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.
Class functions that begins with double underscore
__ are called special functions in Python.
This is because, well, they are not ordinary. Example:
To overload the
+ operator, we will need to implement
__add__() function in a class.
With great power comes great responsibility. We can do whatever we like, inside this function.
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
p1 = Point(2, 3)
p2 = Point(-1, 2)
print(p1 + p2) # print (1,5)