Magic methods in Python for 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.
+ 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
str class and
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
__add__() is used to overload
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: