Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Operator Overloading in Python

$
0
0

In this post we’ll learn about Operator overloading in Python which is one of the OOPS concept like method overloading and method overriding. Operator overloading is an example of polymorphism as the same operator can perform different actions.

What is operator overloading

Operator overloading as evident from the name itself means the ability to overload the operator to provide extra functionality in addition to its real operational meaning. For example ‘+’ operator which is used with numbers to perform addition operation. But ‘+’ operator when used with two strings concatenate those Strings and merge two lists when used with lists in Python. It is possible because ‘+’ operator is overloaded in str and list class to provide extended functionality.


Python Operator overloading for ‘+’ operator


#using + operator with integers to add them
print(5 + 7)
#using + operator with Strings to concatenate them
print('hello ' + 'world')
a = [1, 2, 3]
b = [4, 5, 6]
# using + operator with List to concatenate them
print(a + b)

Output


12
hello world
[1, 2, 3, 4, 5, 6]

When is Operator overloading required

In the above example ‘+’ operator worked with Strings and Lists because it is already overloaded to provide that functionality for String and List. What if you want to use operator with custom objects. For example if you want to use ‘+’ operator with your custom class objects.

In the example there is a class Point with two variables x and y. Two objects of Point class are instantiated and you try to add those objects with the intention to add the data (p1.x + p2.x) and (p1.y + p2.y) of these two objects.


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

p1 = Point(1, 2)
p2 = Point(3, 4)

print(p1+p2)

Output


Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 9, in <module>
print(p1+p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

As you can see trying to add two objects results in an error ‘unsupported operand type(s) for +’ because ‘+’ operator doesn’t know how to add these two objects.

What you want to do here is to add the data (p1.x + p2.x) and (p1.y + p2.y) of these two objects but that will require operator overloading as that is some extra functionality that you want ‘+’ operator to perform.

Operator overloading in Python

For all operators internally Python defines methods to provide functionality for those operators. For example functionality for ‘+’ operator is provide by special method __add__(). Whenever ‘+’ operator is used internally __add__() method is invoked to do the operation.

Internal methods that provide functionality for the operators are known as magic methods in Python. These magic methods are automatically invoked when corresponding operators are used.

When you want any operator to work with custom objects you need to override the corresponding special method that provides functionality for that operator.

Python Operator overloading example

In the example there is a class Point with two variables x and y. Two objects of Point class are instantiated and you try to add those objects with the intention to add the data (p1.x + p2.x) and (p1.y + p2.y) of these two objects. In order to successfully do that magic method __add__() has to be overridden in your class to provide that functionality.

Overloading ‘+’ operator to work with custom objects


class Point:
def __init__(self, x, y):
self.x = x
self.y = y
#overriding magic method
def __add__(self, other):
return self.x + other.x, self.y + other.y

p1 = Point(1, 2)
p2 = Point(3, 4)

print(p1+p2)

Output


(4, 6)

Magic methods in Python

Magic methods in Python are the methods prefixed with two underscores and suffixed with two underscores. These magic methods are also known as Dunders (Double UNDERscores) in Python. In this section magic methods for some of the important operators are listed.

Magic methods for arithmetic operators

OperatorMagic MethodDescription
+__add__(self, other)Additive operator
-__sub__(self, other)Subtraction operator
*__mul__(self, other)Multiplication operator
/__truediv__(self, other)Division with fractional result
%__mod__(self, other)Remainder operator
//__floordiv__(self, other)Division with integer result, discarding any fractional part
**__pow__(self, other)Return a to the power b, for a and b numbers.
@__matmul__(self, other)Matrix Multiplication. Available from version 3.5

Magic methods for Comparison operators

OperatorMagic MethodDescription
<__lt__(self, other)less than
<=__le__(self, other)less than or equal to
==__eq__(self, other)equal to
!=__ne__(self, other)not equal to
>__gt__(self, other)greater than
>=__ge___(self, other)greater than or equal to

Magic methods for compound assignment operators

OperatorMagic MethodDescription
+=__iadd__(self, other)Addition assignment
–=__isub__(self, other)Subtraction assignment
*=__imul__(self, other)Multiplication assignment
/=__itruediv__(self, other)Division assignment
%=__imod__(self, other)Modulus assignment
//=__ifloordiv__(self, other)Division with integer result, discarding any fractional part
**=__ipow__(self, other)Return a to the power b, for a and b numbers.
@=__imatmul__(self, other)Matrix Multiplication. Available from version 3.5

Magic methods for unary operators

OperatorMagic MethodDescription
+__pos__(self, other)Unary plus operator; indicates positive value
-__neg__(self, other)Unary minus operator; negates an expression
~__invert__(self, other)Returns the bitwise inverse of the number

Overloading ‘*’ operator in Python


class Point:
def __init__(self, x):
self.x = x
#overriding magic method
def __mul__(self, other):
return self.x * other.x

p1 = Point(12)
p2 = Point(5)
print(p1*p2)

Output


60

Overloading comparison operator (>) in Python


class Person:
def __init__(self, name, salary):
self.name = name
self.salary = salary
#overriding magic method
def __gt__(self, other):
return self.salary > other.salary

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)
print(obj1.name, 'earns more than', obj2.name, '-', obj1 > obj2)

Output


John earns more than Natasha - False

That's all for this topic Operator Overloading in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Inheritance in Python
  2. Constructor in Python - __init__() function
  3. Abstract Class in Python
  4. self in Python
  5. Nonlocal Keyword in Python With Examples

You may also like -

  1. How to Pass Command Line Arguments in Eclipse
  2. Reflection in Java
  3. Java Concurrency Interview Questions And Answers
  4. Marker Interface in Java
  5. Find Largest And Smallest Number in The Given Array - Java Program
  6. Spring JdbcTemplate Insert, Update And Delete Example
  7. Transaction Management in Spring
  8. HDFS Commands Reference List

Viewing all articles
Browse latest Browse all 938

Trending Articles