Magic methods in Python for Operator Overloading
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.
https://gist.github.com/IndhumathyChelliah/0026616c1ad414bc0e755f9da0b1444e
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
https://gist.github.com/IndhumathyChelliah/1796a11486d474db8b4fb73700305e4e
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.
https://gist.github.com/IndhumathyChelliah/4ed01bdf7e28f8cd7eb2ff2fd0fb484e
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.
https://gist.github.com/IndhumathyChelliah/83e8293d76eb8f8cc1584d96f3e143b6
- Arithmetic Operators and Associated Magic methods:
https://gist.github.com/IndhumathyChelliah/f88c926fdc19f4d338889ceca1b1bdb3
Example for how to overload arithmetic operators in Python.
https://gist.github.com/IndhumathyChelliah/3ec659580448e29c4cc7b2d0d3095c07
- Comparison Operators and its Magic methods:
https://gist.github.com/IndhumathyChelliah/c013d49727fd4eeb2e268dd0522d87b4
Example for how to overload comparison operators in Python.
https://gist.github.com/IndhumathyChelliah/6f02e2e14b69f2d96f348f687420d788
- Assignment Operator and associated Magic methods.
https://gist.github.com/IndhumathyChelliah/a2387f7e3196369f224bcb0bb46cf763
Examples of how to overload assignment operators in Python:
https://gist.github.com/IndhumathyChelliah/a773695e0ac263d2465915afc8fb0013
- Unary Operators and associated Magic Methods:
https://gist.github.com/IndhumathyChelliah/f4757414936e21d2413f0994c28310af
Examples of how to overload unary operators in Python:
https://gist.github.com/IndhumathyChelliah/f2e1f50e18ecbe916be4b4f98f7a4a2d
Resources:
https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee