Menu Close

Dunder or Magic Methods in Python

magic methods in python

In this article, we are going to learn all about Python dunder methods or magic methods. Magic methods in Python are special methods that are mainly used for operator overloading In python, Dunder methods are also known as magic methods and special methods.

It is called the magic method because it adds magic to your python program. You can not access the magic methods directly. Magic methods invoke internally from the class for a certain task.

In this guide, we will see what is dunder methods are and how to use them in our python program using some suitable examples.

What is Dunder or Magic methods in Python?

Python magic methods are playing an important role. Dunder methods always start and end with a double underscore ( __ ). For example, __add__() is a dunder method.
There are a lot of dunder methods available in Python which are used for a certain task. You can not access the magic method directly, the Magic method access by class internally for a certain task.

For example: When you add two numbers in our python program using the + operator, internally the __add__() method is called.


Adding two numbers using + operator.

a = 12
b = 30
result = a + b

As you can see In the above example when we have added two numbers a and b using + operator, + operator internally calls __add__() method.
You can write the above program just like the below example.


a = 12
b = 30
result = a.__add__(b)

Why use Magic methods in Python

In Python, Magic methods in Python are mainly used for operator overloading and so many more. There are a lot of magic methods available in python which are used for different tasks.
As you know that + operator is used to adding two numbers as well as concatenate two strings.

In Python, the Built-in class defines lots of magic methods. To see all methods you have to use the dir() function.
For example, To get all the all magic methods of int class use the dir() function.


Few Python magic methods are: __init__(), __add__(), __str__(), __repr__(), etc.


In Python, __init__() is called automatically when an instance or object of the class is created like a constructor.
Let see, How the instance __init__() method is calling or not during object creation.


class Student:
	def __init__(self):
		print("Magic methods in Python")
St = Student()

The output will be:- Magic methods in Python


In Python, When we create a user define a class and try to add two objects of that class, Then we got a TypeError.
We can solve this problem using the __add__() magic method.


class Student:
	def __init__(self, marks):
		self.marks = marks
	def __add__(self, other):
		print("The Addition of marks of two students is:- {}".format(self.marks + other.marks))
st1 = Student(12)
st2 = Student(30)
st1 + st2


The addition of marks of two students is:- 42

In the above example, we created a user-defined class Student and add two objects of Student are st1 and st2 using the + operator.When we use + operator, it is internally called __add__() methods just like st1.__add__(st2).


__str__() is a built-in function in Python, which is used for the string representation of objects.


class Student:
	def __init__(self, name): = name	
	def __str__(self):
		return "Student Name is:- {}".format(
St = Student('Vishvajit')


Student Name is:- Vishvajit


__repr__() is similar to the __str__() methods.


class Student:
	def __init__(self, name): = name	
	def __repr__(self):
		return "Student Name is :- {}".format(
St = Student('John')


Student Name is:- John

Operator overloading using comparison operator:

Python provides various magic methods for compare values.
In the below example, we have used magic methods ( __lt__(), __gt__() and __eq__() ) to comparison three numbers.

Learn Python From Scratch


class Compare:
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        print(f"{self.a} is less than {other.a}")
    def __eq__(self, other):
        print(f"{self.a} and {other.a}")
    def __gt__(self, other):
        print(f"{self.a} is greater than {other.a}")

print("----- Less than operator ------")     
a1 = Compare(12)
a2 = Compare(20)
a1 < a2

print("----- Greater than operator ------")     
a1 = Compare(12)
a2 = Compare(10)
a1 > a2

print("----- Equal to operator ------")     
a1 = Compare(12)
a2 = Compare(12)
a1 == a2


----- Less than operator ------
12 is less than 20

----- Greater than operator ------
12 is greater than 10

----- Equal to operator ------
12 and 12


I hope after completing this article, you don’t have any confusion regarding magic methods in Python. If you want to learn Python programming, Then you can’t ignore magic methods and dunder methods in Python because magic methods play the most important role in every python program internally.

If this is article is helpful for you, please share and keep visiting for further Python tutorials.

For more about magic methods in Python:- Click Here

Python Program to Count and Display Vowels from a String
Python Variables

Related Posts