Everything you need to know about “Magic methods” in Python
Wanna add some magic to your code? then use magic methods.
Magic methods are some built-in methods in Python used to provide some special functionalities. They work as Constructors. The arguments provided to magic methods will run automatically when the object is created. Magic methods are defined by using two underscores called Dunders.
Syntax: def __init__(self,args,args)
__init__() is the most commonly used Magic/Dunder method use to initialize objects.
Consider a simple Python program that performs the addition of two numbers.
print(5+6)#output=11
As you can see the output will be 11.
Similarly if we two Strings with a ‘+’ operator then the results will be different.
print(‘5’+’6')#output= 56
It will concatenate the two strings. This proves that using the ‘+’ operator for numbers will be different than using ‘+’ operators for strings. So, here in the above example for the addition of two integers, we have used the __add__() magic method.
Check the example below:
a=5print(a.__add__(6))#Output: 11
There are numerous Magic/Dunder methods to provide the desired functionality to your Python program and for that, you can check Python documentation for dunder methods.