Magic Methods in python


 Magic methods

It is also called Dunder method in python. These are the methods in python having two prefix and two suffix underscores. Dunder means "Double under(underscore)". These are commonly used for operator overloading. Few examples of magic methods are given below...

__init__, __add__, __len__, __repr__, __div__ etc.


List of some Arithmetic magic methods in python

1. __add__(self,other):- To get called on odd operation using + operator.

2. __sub__(self,other):- To get called on subtraction operation using - operator.

3.__mul__(self,other):- To get called on multiplication operation using * operator.

4. __div__(self,other):- To get called on division operation using / operator.

5.__floordiv__(self,other):- To get called on floor division operation using // operator.

6.__mod__(self,other):- To get called on modulo operation using % operator.

7.__pow__(self,other):- To get called on calculating the power using ** operator.


List of some Comparison magic methods in python

1.__lt__(self,other):- To get called on comparison using less than (<) operator.

2.__gt__(self,other):- To get called on comparison using greater than (>) operator.

3.__le__(self,other):- To get called on comparison using less than or equal to (<=) operator.

4.__eq__(self,other):- To get called on comparison using equal to equal to (==) operator.

5.__ne__(self,other):- To get called on comparison using not equal to (!=) operator.

6.__ge__(self,other):- To get called on comparison using greater than or equal to (>=) operator.

Example

for add_method:- When you add two numbers using the + operator internally, the __add__ method will be called

>>> num=10

>>> num+5                       # it will give the result 15

>>> num.__add__(5)       # it will also give the result 15

Here when you do (num+5) the + operator calls the __add__(5) method. You can also call num.__add__(5) directly will give the same result. However magic methods are not meant to be called directly, but internally through some other methods or actions.

Note 

Built-in classes in python define many magic methods. If we want to see the magic methods in any python class then we can use the dir() function to see the number of magic methods available in the class.

Example

>>> dir(int)

It will print all the magic methods are available in the int class.














No comments:

Post a Comment