Open In App

Python __init__ vs __new__

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, __init__ and __new__ are part of a group of special methods in Python commonly referred to as dunder methods or magic methods. The term "dunder" is short for "double underscore," reflecting the naming convention with double underscores at the beginning and end of the method names.

Python __new__

__new__ method in Python is a special method that's responsible for actually creating a new instance of a class. Think of it as the step where the object itself comes into existence, even before it gets initialized with specific values. It gets called automatically before the __init__ method, which is used to set up the object.

Let's understand this with an example :

Python
class CustomObject:
    def __new__(cls, value):
      
        # Create a new instance
        instance = super().__new__(cls)
        
        # Attach an attribute during creation
        instance.value = value
        return instance


# Creating objects
obj1 = CustomObject(10)
obj2 = CustomObject(20)

print(obj1.value) 
print(obj2.value)  

Output
10
20

Explanation :

  • instance = super().__new__(cls): Calls the parent class’s __new__ to create an instance.
  • instance.value = value: Adds a custom attribute during creation.
  • return instance: Returns the newly created instance; object creation fails if not returned.

Python __init__

__init__ method in Python is a special method known as the initializer or constructor. It is called automatically when a new instance (object) of a class is created. Its primary purpose is to initialize the object's attributes (or set up its state) after the object has been created.

Let's understand this with an example :

Python
class SimpleObject:
    def __init__(self, value):
      
        # Initialize the instance
        self.value = value


# Creating objects
obj1 = SimpleObject(10)
obj2 = SimpleObject(20)

print(obj1.value)  
print(obj2.value) 

Output
10
20

Demonstration of __new__ and __init__ in Instance Creation

In Python, __new__ and __init__ are two special methods that play distinct roles in the object instantiation process:

Python
class MyClass:
    def __new__(cls, *args, **kwargs):
      
        print("GeeksforGeeks")
        
        # Calling the parent class's __new__ method to create the instance
        instance = super().__new__(cls)
        return instance

    def __init__(self, value):
        # This method initializes the object after it's created
        print(f"{value}")
        self.value = value

# Create an instance of MyClass
obj = MyClass(10)

Output
GeeksforGeeks
10

Explanation:

  • __new__ method is responsible for creating the instance. It’s called before __init__ and is where the object itself is actually created.
  • The super().__new__(cls) call creates the new instance, and then it’s returned so that Python can continue with the initialization.
  • After the instance is created by __new__, the __init__ method is called to initialize the object’s attributes.

Major Differences between __new__ and __init__

Aspect

__new__

__init__

Purpose

Responsible for creating a new instance of a class. It is called first when a new object is being created.

Responsible for initializing the instance after it has been created. It sets the initial state of the object by assigning values to instance variables.

When They Are Called

Called before __init__. It is used to control the creation of the object.

Called after __new__ and is used to initialize the newly created object

Return Value

Must return the newly created instance (object), which is then passed to __init__.

Does not return anything. Its role is only to initialize the object after it's created.

Common Usage

Typically rarely overridden. It is most commonly used when dealing with immutable objects.

Frequently overridden to initialize attributes of an object. It is used in most classes to set up the state of the object.

Inheritance Behavior

It is called by the class itself or its metaclass. It must return an instance of the class, and in the case of inheritance, it will call super().__new__(cls) to create an instance.

It is called on the instance of the object, and in the case of inheritance, it is called for each subclass instance.


Next Article
Article Tags :
Practice Tags :

Similar Reads