Dunder/Magic Methods in Python

In Python methods having names that have leading and trailing double underscores like __init__ are called Dunder(Double Underscores) Methods. These are often also called Magic Methods as these can be used for adding some magic to Python user-defined classes. Dunder methods can also be used to emulate behaviour of built-in types to user defined objects.
Below is a table containing all of Python’s Dunder Methods.

Dunder/Magic Method
__add__(self, y)
__contains__(self, y)
__eq__(self, y)
__ge__(self, y)
__getitem__(self, y)
__gt__(self, y)
__hash__(self, y)
__int__(self, y)
__iter__(self, y)
__le__(self, y)
__len__(self, y)
__It__(self, y)
__mod__(self, y)
__mul__(self, y)
__ne__(self, y)
__neg__(self, y)
__repr__(self, y)
__setitem__(self, y)
__str__(self, y)
__sub__(self, y)

Just a quick point – In the above table y is a parameter

Why Python have Dunder Methods?

Python’s creators want to have some way for Programmers to define Methods for classes which are not built into language itself. But also allocating some names like call for a Programmer Defined method seems unreliable and there may be some better use of these into language. That’s why Python Creators come up with idea of using Double Underscores for defining these methods, as name of these methods is wrapped inside double underscores from both side, these remain unique. And other simple unique words like call, repr, setitem can be used for other purposes in language.

Defining Dunder Methods for Class in Python

Let’s see How Dunder Methods can be defined using Python Interpreter. So If you want to follow along with me, then open up Python Interpreter in your PC.

Defining __len__() Dunder Method

This Dunder method can used for defining length inside a class. Below is a code example explaining this

>>> class Testing:
...     pass
... 
>>> obj = Testing()
>>> len(obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'Testing' has no len()

In the above example – You can clearly see a TypeError being raised by len() Function as length of obj is not defined inside class Testing.
But by using __len__() Function, length can be explicitly defined inside Testing Class.

>>> class Testing:
...     pass
...     def __len__(self):
...             return 10
... 
>>> obj = Testing()
>>> len(obj)
10

Here you can clearly see that Python’s Built-in Function len() is calling __len__(self) defined inside Testing class. Note here that if object is some instance of Python’s Built-in class then len() function will call length function defined inside Built-in class.

Defining __str__() Dunder Method

Every built-in Python Class have a method which returns Human Readable String Representation of Data when some object created from that class is passed to print() function as a parameter. But for classes which your defining, you can add __str__() function.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return "Person: {}, Age: {}".format(self.name, self.age)
>>> person = Person('Elon Musk', 50)
>>> print(person)
Person: Elon Musk, Age: 50
>>> person
<__main__.Person instance at 0x10d4112e3>

Final Thoughts

Dunder/Magic methods can do little bit of magic as these can be used for defining explicit class methods for classes which are not built-in language itself rather are user defined. Here I’ve covered examples of just two dunder methods – __len()__ and __str__() but if your interested you can also try out other methods list in the table at the top of this page in Python Interpreter.

Any feedback regarding this article is more than welcome, please if you want to say something then do so in comments below.
Happy Coding 🥳

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts