What are Python Dunder Methods or Magic Methods?

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Python dunder methods are the special predefined methods having two prefixes and two suffix underscores in the method name. Here, the word dunder means double under (underscore). These special dunder methods are used in case of operator overloading ( they provide extended meaning beyond the predefined meaning to an operator). Some of the examples of most common dunder methods in use are __int__,__new__, __add__, __len__, and __str__ method.

Python dunder methods can be easily understood by visualizing a contract between your implementation and the Python interpreter. One of the main terms of the contract involves Python performing some actions behind the scenes under some given circumstances.

These Python dunder methods are invoked internally from the class based on a certain condition or action. Like, when you add two numbers using the + operator, then the __add__ dunder method will be invoked, and the __init__ method will be invoked when an instance of a class is created and it behaves in the same way like the constructors behave in certain other programming languages such as C++, Java, C#, PHP, etc. Let's see the implementation and examples of some of the most common dunder methods in Python.

Implementation of Python Dunder Methods

In this section we will see the simple implementation of a few of the common dunder methods in Python:

The output of the above code would be the location of the string object given by:

The above piece of code only focuses on returning the memory address or the location of the string object. Now, let us add a __repr__ method to represent our object.

In this code, we have now added a new dunder function to print the string object

The output of the above code is:

There is a specific dunder method to add a string to this string object. If we try to do it without the dunder method, then it will throw an error. Let's see how we can do it with and without using the __add__ dunder method.

The above code will throw the type error because of adding the unsupported operand types, one being the type of string and another being the string object.

We can do the same thing by using the __add__ method to the string class.

Now, the two operand types are the same and we can concatenate them

The desired output would be:

Examples of Python Dunder Methods

Let us see a few of the examples of using different Python dunder methods:

1. str Method:

One of the most common magic methods is the str() method in Python. When we have to return a string then we call this str() built-in function to return a string from the object parameter.

But, internally the str() function calls the __str()__ magic method defined in the int class. This is why it is called a magic method!

For example, str('12') returns '12'. When invoked, it calls the __str()__ method in the int class. So, when str('12') is equal to 12, and it is also equivalent to int.__str__('12').

Let's see the example code for this:

To return the string, we can call the object on the Employee class:

Here, the str() function internally calls the __str__() method defined in the Employee class.

2. add() Method:

The magic method __add()__ performs the addition of the specified attributes of the objects. Internally, the addition of these two distance objects is desired to be performed using the overloading + operator.

Let's see an example of this:

Suppose we have a distance class and we need to perform the addition of the ft and inch attributes of two objects. Now, let's run the above Python script to verify the internal functioning of the overloaded operation of the + operator.

This will give the desired addition operation between different attributes of an object.

3. ge() Method:

The __ge__ method is the magical method that gets invoked when the >= operator is used and it returns True or False, and accordingly, the appropriate message can be displayed based on the result obtained. Let's see the same above example to overload the >= operator in the distance class.

Output

As you can see from the output above, this method will return the boolean result based on the inputs provided.

4. init() Method:

The __init__ method works similarly as constructors work in other programming languages. It is automatically invoked during the time of the creation of an instance of a class. It gets invoked without any call. In other words, this method is invoked when an object is formed from a class to permit the class to populate its properties. Let's see one example of this:

The above piece of code returns the memory location of the string's object.

The output of the above code would be:

5. new() Method:

It is one of the most popular dunder methods which other languages such as Java, cpp, and C# use to create a new instance of a class. In Python, the __new()__ magic method is implicitly called before the __init()__ method. The __new()__ method returns a new object, which is then initialized by __init()__ method.

Let's see an example to create an instance of a given class:

The above example will produce the following output when you create an instance of the Employee class.

Thus, we can verify that the __new__() method is called before the __init__() method.

6.repr Method:

A class instance can be represented as a string using this magic method. It gives back the value sent to the eval function's string representation and by default, the custom class object provides a string in angle brackets containing the object’s name and address. We will see the same example that we took above for the __init__ method, along with the addition of the __repr__ method:

Now, the output successfully displays the string which we provided.

Conclusion

  • Python dunder methods are the special predefined methods in Python having two prefixes and two suffix underscores in the method name.
  • Python dunder methods are also known as the magic methods because of the fact that they are internally called by the class in response to a particular action; they are not intended to be called directly by the user.
  • Python dunder methods can be easily understood by visualizing a contract between your implementation and the Python interpreter. One of the main terms of the contract involves Python performing some actions behind the scenes under some given circumstances.
  • The __add()__ method is called internally when you use the + operator to add two numbers.
  • The __init__() method is automatically invoked during the time of the creation of an instance of a class. It is called a magic method because it is called automatically by Python.
  • This __repr__ magic method is used to represent a class instance in a string and it returns the string representation of the value supplied.
  • The __new__() magic method is implicitly called before the __init__() method. It returns a new object, which is then initialized by __init__().
  • The __ge__ method is the magical method that gets invoked when the >= operator is used and it returns True or False.
  • The built-in str() function returns a string from the object parameter and it internally calls the __str__() method defined in the int class.
  • You can always add different functionality to your custom class using the appropriate magic methods. These methods are pure magic and help us improve the functionality of our classes.
  • There are many other different types of Python dunder methods like __len__ , __sub__, __mul__, __call__, etc..

Explore Scaler Topics Python Tutorial and enhance your Python skills with Reading Tracks and Challenges.

See Also: