Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
__new__()
3.
__add__()
4.
__repr__()
5.
__len__()
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Magic-Dunder Methods

Author Malay Gain
1 upvote

Introduction

Magic methods are a special kind of method used for operator overloading. Magic methods have double scores on both side of the method name. That’s why these methods are also known as Dunder methods. Magic methods are not called directly; these are invoked implicitly on certain action. Some examples of magic methods are

__init__, __add__, __repr__ etc.

Let’s know about some commonly used magic methods.

Recommended Topic, Floor Division in Python and Convert String to List Python.

__new__()

This magic method is implicitly called by __init__( ) method to create new instance of a class i.e, object. __new__() method returns a new object that is initialized by  __init__( ) method.

#a class to denote student 
class Student:
  
  def __new__(cls):
    print ("__new__  method is called")
    instance = object.__new__(cls)
    return instance
    
  #constructor in Python
  def __init__(self):
    print ("__init__  method is called")
    print("student object initialized")
  
student= Student()

Output

__new__  method is called
__init__  method is called
student object initialized

If we observe the outputs, we can see  __new__() method is executed before __init__( ) method.

__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!

Live masterclass