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 dunder methods are and how to use them in our Python program using some suitable examples.

What are Dunder or Magic methods in Python?

Python magic methods play an important role in Python programming. 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 is accessed by the 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 the + 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 the + operator, the + operator internally calls the __add__() method.
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 different tasks.
As you know the + operator is used to add 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 magic methods of int class use the dir() function.

dir(int)

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

__init__()

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

Example:


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

The output will be:- Magic methods in Python

__add__()

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

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 added 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__()

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

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 comparing values.
In the below example, we have used magic methods ( __lt__(), __gt__() and __eq__() ) to comparison three numbers.

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

Conclusion

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 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 with Examples

Related Posts