Magic Methods or Dunders in Python Programming

Magic Methods or Dunders: Magic methods or dunders in python are the methods which are having two prefix and suffix underscores(__) in the method name ie. (__methodname__()). The __init__ method is called automatically when an object or instantiation of class is created. Dunder means double(__) underscore.These methods are used mainly for operator overloading purposes.

Till now we have discussed about constructor (__init__), which are also a type of magic methods. Different magic methods have their different functionalities. Here are some magic functions available in Python.

Some of the magic functions available in Python:
1).
__init__()
2). __repr__()
3). __add__()
4). __len__()
5). __mul__()

(i). __init__(): We have already studied about __init__() method ie. constructor in python. Constructor in python is a type of magic function which is called automatically during object creation of object. Constructor is used to initialize the instance variable of a class during class instantiation.

Example 1: 

#Magic_method__init__()_example

class Test:
    def __init__(self, greet):
        self.greet = greet
    
obj = Test("Hey")
print(obj)

Output:

#Output
<__main__.Test object at 0x7f9b42789c50>

It returned us the memory address where our object is stored.

 

(ii). __repr__(): Above __init__ method returned us the object memory address. But what if we want to get our object itself. Let’s see what __repr__ method do for us:

Example 1:

#Magic_method__repr__()_example

class Test:
    def __init__(self, greet):
        self.greet = greet
    
    def __repr__(self):
        return 'object is: {}'.format(self.greet) 
    
obj = Test("Hey")
print(obj)

Output:

#Output
object is: Hey                                                                                      

It represented or returned us the value stored at object instead of returning the memory address.

Important: So in above example “Hey” is the string type value that we have passed to our constructor to store it in class instance variable. And later we used __repr__()method to get the object as result. As we have passed string type value, then it is correct if we add or concatenate string. Let’s do this:

Example 2:

#Magic_method__repr__()_example

class Test:
    def __init__(self, greet):
        self.greet = greet
    
    def __repr__(self):
        return 'object is: {}'.format(self.greet) 
    
obj = Test("Hey")
print(obj + "pythonlobby")

Output:

#Output
TypeError: unsupported operand type(s) for +: 'Test' and 'str'                                                                                     

Now it returned the error. It happened because, obj here is not of string type, its an object type value. You can check its type by using type() function ie. print(type(obj)) . Now let’s see what __add__ method do for us.

 

(iii). __add__(): This method is invoked automatically when we perform any addition operation using ‘+’ operator.
we use var_1 + var_2 to get the multiplication result of both variables. But at the backend __add__() constructor called automatically.

Example 1:

#Magic function __add__ example

#Normal_program_using_multiplication_operator
var_1 = 23
var_2 = 32
add = var_1 + var_2
print(add)

Output:

#Output
55

Example 2:

#Magic_function_program_using_multiplication_operator
var_1 = 23
var_2 = 32
add = var_1.__add__(var_2)
print(add)

Output:

#Output
55

Example 2: We can also over write the __add__ method based on our requirement. Let’s discuss by an example: We will take example that we have discussed before in __repr__ method.

#Magic_method__add__()_example

class Test:
    def __init__(self, greet):
        self.greet = greet
    
    def __repr__(self):
        return 'object is: {}'.format(self.greet)
        
    def __add__(self, otherValue):
        return self.greet + otherValue
    
obj = Test("Hey")
print(obj + " Pythonlobby")

Output:

#Output
Hey Pythonlobby

 

(iv). __len__(): This method is invoked automatically when we perform any operation on collection using len() function to count its length. Actually in background the method called is __len__().
we use len() function to get length of some collection (lists, strings, dictionary, tuples etc.). But at the backend __len__() magic method is called automatically. Let’s discuss by an example:

Example 1: 

#Magic_method__len__()_example

class Test:
    def __init__(self, greet):
        self.greet = greet
    
    
obj = Test("Hey")
print(len(obj.greet))    #normal method to get length

print(obj.greet.__len__())   #magic method to get length

Output:

#Output
3                                                                                                                             
3

 

(v). __mul__(): Same as __add__ method, this method is invoked automatically when we perform any multiplication operation using ‘*’ operator.
we use var_1 + var_2 to get the multiplication result of both variables. But at the backend __mul__() constructor called automatically.

Example 1: 

#Magic function __mul__ example

#Normal_program_using_multiplication_operator
var_1 = 23
var_2 = 32
muls = var_1 + var_2
print(muls)

Output:

#Output
736

Using Magic Function

#Magic_function_program_
var_1 = 23
var_2 = 32
muls = var_1.__mul__(var_2)
print(muls)

Output:

#Output
736