Magic methods Python are also known as dunder methods or special methods. Why are they so named? It is because they are basically used to over-write or imitate the general behavior of built-in functions.

So, what is the importance of magic methods? Magic Methods are basically the everything in object-oriented Python. They are special methods which can be defined to make your classes magical. Later on, we will see how. They are usually accompanied and followed by double underscores (eg. __init__). Hence, the name “Dunder Methods”.

Thus, in this post, I have set out to provide some layman, example-driven documentation for Python’s magic methods. I hope you enjoy it. One can use this as a guide, a reference, or a refresher; as it is a user-friendly guide to Python’s magic methods.

Some of the common magic methods Python

We’ll discuss these methods based on their object usefulness (an object is an instance of a class). The three categories we’ll be focusing on are

  • Object Initialization method
  • Then, Object Representation Method
  • Object Mathematical Operation Method

To understand these methods better, we’ll use a specific business scenario.

Let’s imagine we have a minimalist online store that sells just tee-shirts. These tee-shirts come in one size, one futuristic design, and have the same price. However, they are made in only in black or white.

As an entry-level inventory manager, you have two basic goals in mind:

– To store the tee-shirt data in one place, in terms of color and inventory count for each color .

– To know the total tee_shirt inventory count.

Let’s assume the minimalist online store decides to store this information in a Python class.

The first method we use when creating a class is the initialization method __init__(), which is actually a magic method. This method, also called a constructor, takes care of setting up the object. Let’s create a TeeShirt class

Above is a simple representation of the tee-shirt class, as it includes just the tee-shirt data. With this magic method, we can easily create black and white tee-shirt objects and find out the necessary attributes, as shown below:

What if, instead of having to call each attribute of an object, you could just print the object variable and get all the useful information about that object?

From the above example, we see that printing the object variable directly didn’t give us much useful information about the meta-data. It just gives some kind of ID that shows it is a TeeShirtclass object,which wealready know.

The Object Representation Method

A good way of being able to view all the attributes at once is with an object representation method called __str__(). Let’s add this into our class as a method:

Now, give it a test run:

Magic Methods Python

Thus, we see above that all metadata can now be viewed by just printing the object variable directly. One of the biggest advantages of using Python’s magic methods is that they provide a simple way to make objects behave like built-in types/functions. In this case , t his method is behaving like a str()type function, as a string representation of the object. Another object representation method is __repr__(), which works in a similar way.

Going back to our amateur inventory manager’s goal…

It would be nice to be able to know the sum of all the shirt inventories. Let’s see what happens when we add both shirt objects together.

Magic Methods Python

Python throws a TypeError. This is because the black_shirt and white_shirtvariables are stillObjectTypes and cannot perform mathematical operationsdirectly.

Let’s see if we can add the objects using their inventory_count attributes.

That seems to do the trick. However, an even nicer way is to add an object operation methodto the TeeShirt class in order to print the object variable without the attributes. Using the magic method __add__()—let’s see how:

Magic Methods Python

Now, give it a test run:

Magic Methods Python

It’s good to note that the importance of this method gets even handier as the class gets more complicated and the object instances multiply.

Check out some other useful magic methods and their functionalities below. This could be a bonus tool for upgrading your Python classes.

Magic Methods Python

Some final tips to keep in mind

  • Everything in Python is an object.
  • One can also use the dir() built-in function on an object to see the magic methods inherited by the class. Try out dir(str)or dir(black_shirt)(if you create a black_shirt object).
  • Also, Magic methods can be used to emulate the behavior of built-in types of user-defined objects. Therefore, whenever you find yourself trying to manipulate a user-defined object’s output in a Python class, remember: magic methods.

SUMMING UP <—> Magic Methods Python

In this post, as you have seen we discussed about the steps to get ourselves acquainted and familiar with Dunder or Magic methods Python. Thus, we are now well accomplished and ready to work our way through the various Magic methods and use them to our advantage in several programs. We see that using Magic Methods our task becomes a bit simpler comparatively than, when not using them.

By and through this article, thus, I suppose I have made myself pretty clear. But, in case, you still have some doubts lingering. Then, please do write to me in the comments section and I am as always, ever-ready to help you. And, also solve your many queries and problems.

Until then bidding you Good-Bye !!! Ok, wait ….. before you go, you may check out my various other posts. Also, for the simple reason, that is, to enhance your knowledge on various other topics of importance. Also, where ??? Here……