Dunder or magic methods in Python

Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.

The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with ‘+’ operator without any explicit typecasting.

Here’s a simple implementation :



filter_none

edit
close

play_arrow

link
brightness_4
code

# declare our own string class
class String:
      
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
          
# Driver Code
if __name__ == '__main__':
      
    # object creation
    string1 = String('Hello')
  
    # print object location
    print(string1)

chevron_right


Output :

<__main__.String object at 0x7fe992215390>

 
The above snippet of code prints only the memory address of the string object. Let’s add a __repr__ method to represent our object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# declare our own string class
class String:
      
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
          
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)
  
# Driver Code
if __name__ == '__main__':
      
    # object creation
    string1 = String('Hello')
  
    # print object location
    print(string1)

chevron_right


Output :

Object: Hello

 
If we try to add a string to it :

filter_none

edit
close

play_arrow

link
brightness_4
code

# declare our own string class
class String:
      
    # magic method to initiate object
    def __init__(self, string):
        self.string = string
          
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)
  
# Driver Code
if __name__ == '__main__':
      
    # object creation
    string1 = String('Hello')
      
    # concatenate String object and a string
    print(string1 +' world')

chevron_right


Output :

TypeError: unsupported operand type(s) for +: 'String' and 'str'

 
Now add __add__ method to String class :

filter_none

edit
close

play_arrow

link
brightness_4
code

# declare our own string class
class String:
      
    # magic method to initiate object
    def __init__(self, string):
        self.string = string 
          
    # print our string object
    def __repr__(self):
        return 'Object: {}'.format(self.string)
          
    def __add__(self, other):
        return self.string + other
  
# Driver Code
if __name__ == '__main__':
      
    # object creation
    string1 = String('Hello')
      
    # concatenate String object and a string
    print(string1 +' Geeks')

chevron_right


Output :

Hello Geeks

 

Reference : docs.python.org.



My Personal Notes arrow_drop_up

A computer science student interested in coding cybersecurity gaming and science

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.