__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
Output
15
__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
Output
Enrollment id of Dhruv is 5105133
__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
Output
5
Must Read, python ord
FAQs
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
Output
15
You can compile it with online python compiler.
Key Takeaways
This article covered Magic-Dunder Methods, special type of methods in Python.
We recommend you to check out the Coding Ninjas Studio Guided Path on Python programming for learning Python language from basics.
Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here.
Happy learning!