__add__()
This magic method is used to add attributes of two objects i.e, class instances. If we define __add__() method in such a way that it adds two object of same class by overloading + operator, the operation obj1 + obj2 adds attributes of the objects by invoking the method implicitly.
class number:
def __init__(self,integer):
self.integer=integer
def __add__(self,obj):
return self.integer+obj.integer
num1=number(5)
num2=number(10)
num1+num2

You can also try this code with Online Python Compiler
Run CodeOutput
15

You can also try this code with Online Python Compiler
Run Code__repr__()
This magic method is used to represent instance of a class in string. __repr__() method is invoked when we try to print object a class by calling print() method. So, we can overload __repr__() method to get customize string representation of any object.
class Student:
#constructor in Python
def __init__(self,name,enr_id):
#instance variable
self.name=name
self.enr_id=enr_id
def __repr__(self):
return f"Enrollment id of {self.name} is {self.enr_id}"
student= Student("Dhruv",5105133)
print(student)#print invokes __repr__ method internally

You can also try this code with Online Python Compiler
Run CodeOutput
Enrollment id of Dhruv is 5105133

You can also try this code with Online Python Compiler
Run Code__len__()
This magic method is used to find length of instance attribute of a class. When len() is called on any object, it returns length of container attribute of the object if __len__() method is defined accordingly inside the class.
class Student:
def __init__(self,name,marks):
#instance variable
self.name=name
self.marks=marks
def __len__(self):
return len(self.marks)
student= Student("Dhruv",[75,80,78,89,65])
len(student) #invokes __len__() method

You can also try this code with Online Python Compiler
Run CodeOutput
5

You can also try this code with Online Python Compiler
Run CodeFrequently Asked Questions
1. What are the magic methods used for comparing object’s attributes?
__eq__() for checking equality, __ne__() for not equality, __gt__() for greater than, __lt__() for checking less than.
2. What is __call__() method?
This magic method is invoked when an object of a class is invoked. We can define this function according to our objective without defining another function as we can call the method by just using the name of the class object.
class Addition:
def __init__(self, val):
self.val = val
def __call__(self, a):
return self.val + a
obj = Addition(5)
print(obj(10)) #calling by object name

You can also try this code with Online Python Compiler
Run CodeOutput
15

You can also try this code with Online Python Compiler
Run Code
You can compile it with online python compiler.
Conclusion
In conclusion, magic dunder methods in Python provide powerful ways to customize object behavior, making classes more intuitive and versatile. Mastering these methods helps in writing cleaner, more Pythonic, and efficient code.
Recommended Readings: