Member-only story
The Magic Method in Python
Learn the Basics of Magic Method With Code
Magic methods are special methods in Python which the programmer doesn’t invoke. Instead, the invocation can happen internally due to specific actions by the class. Learning about this method will help with the working of parts working of the program. This article let us learn about the exciting magic method, also known as the Dunder method.
Why is it known as the Dunder method? A few methods have double underscore before and after the method name. Dunder abbreviates to Double underscore.
Magic Method Invocation:
Specific actions in the program cause invocation of the magic method. Here is a scenario where a magic method is invoked. Using the “+” operator in this program internally invokes the _ _add_ _ magic method.
num = 100result = num + 10
result1 = num.__add__(10)print(result)
print(result1)
The program result and result1 both should give the same output. The int class calls it to add a magic function when the addition(+) operator is used.
Magic Methods in a Class:
Every class has a few built-in magic methods and attributes. Create a class and check the magic…