A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/dunder-magic-methods-python/ below:

Dunder or magic methods in Python

Dunder or magic methods in Python

Last Updated : 07 Aug, 2024

Python Magic methods are the methods starting and ending with double underscores '__'. They are defined by built-in classes in Python and commonly used for operator overloading. 

They are also called Dunder methods, Dunder here means "Double Under (Underscores)".

Python Magic Methods

Built in classes define many magic methods, dir() function can show you magic methods inherited by a class.

Example:

This code displays the magic methods inherited by int class.

Python
Output
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '_...

Or, you can try cmd/terminal to get the list of magic functions in Python, open cmd or terminal, type python3 to go to the Python console, and type:

>>> dir(int)

Output:

Python Magic Methods

Below are the lists of Python magic methods and their uses.

Initialization and Construction

Numeric magic methods

Arithmetic operators

String Magic Methods

Comparison magic methods

Dunder or Magic Methods in Python

Let's see some of the Python magic methods with examples:

1. __init__ method

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 the '+' operator without any explicit typecasting. 

Python
# 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)

Output
<__main__.String object at 0x7f538c059050>
2. __repr__ method

__repr__ method in Python defines how an object is presented as a string.

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

Python
# 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)

If we try to add a string to it:

Python
# 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')

Output:

TypeError: unsupported operand type(s) for +: 'String' and 'str'
3. __add__ method

__add__ method in Python defines how the objects of a class will be added together. It is also known as overloaded addition operator.

Now add __add__ method to String class : 

Python
# 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')

We have discussed some of the Python magic methods or Dunder methods. Magic methods in Python can be used to different functionalities in your class.

Hope you learn about Python magic methods from this article, and use it in your projects.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4