Python’s Approach to Operator Overloading

Magic methods in Python for Operator Overloading

Photo by Chris Lawton on Unsplash

Operator Overloading:
Operator Overloading in Python is the ability of single operator to perform more than one operation based on class or type of operands.
Ex. + operator is used to add two numbers and used to concatenate two strings or merge two lists.

How to overload operators in Python:
When we use operators in Python,special method or magic method is automatically invoked that is associated with the particular operator.
Ex.When we use + operator, magic method __add__() is automatically invoked.
In the below example + operator is overloaded by int class,str class and list class

When we try to add two objects from user defined class,it will raise TypeError. Since Python doesn’t know how to add two objects together.

Operator Overloading is achieved by using special method/magic method in class definition.These method has leading and trailing double underscores__.Magic method __add__() is used to overload + operator.
We have to define this magic method in class and operators work according to the behavior mentioned in the method.

  • Arithmetic Operators and Associated Magic methods:

Example for how to overload arithmetic operators in Python.

  • Comparison Operators and its Magic methods:

Example for how to overload comparison operators in Python.

  • Assignment Operator and associated Magic methods.

Examples of how to overload assignment operators in Python:

  • Unary Operators and associated Magic Methods:

Examples of how to overload unary operators in Python:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s