Menu Close

Dunder or 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 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.

Example:

Adding two numbers using + operator.

a = 12
b = 30
result = a + b
print(result)

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

Example:

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

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 the different task.
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, For example, To get all the all magic methods of int class use the dir() function.

dir(int)

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

__init__()

In Python, __init() is called automatically when a instance or object of class is created like constructor.
To see, instance init() method is calling or not during object creation.

Example:

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

Output will be:- Magic methods in Python

__add__():

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

Example:

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

Output:

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 st1 and st2 using the + operator.When we use + operator, it is internally called __add__() methods just like st1.__add__(st2).

__str__():

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

Example:

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

Output:

Student Name is:- Vishvajit

__repr__():

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

Example:

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

Output

Student Name is:- John

Operator overloading using comparison operator:

Python provides various magic methods for comparison values.
Here we will use __lt__(), __gt__() and __eq__() megic method for comparison three numbers.

Learn Python From Scratch

Example:

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("\n")
print("----- Greater than operator ------")     
a1 = Compare(12)
a2 = Compare(10)
a1 > a2


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

Output:

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


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


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

Conlcusion

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.

Fore more about magic methods in Python:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts