DEV Community

Cover image for Demystifying Python Constructors: Understanding the Roles of __new__ and __init__
tahsinsoyak
tahsinsoyak

Posted on

Demystifying Python Constructors: Understanding the Roles of __new__ and __init__

Mastering Python Constructors: A Comprehensive Guide to Utilizing new and init for Optimal Object Creation and InitializationIn Python, the constructor method is invoked with new for object creation and init for initialization. Quoting from the Python documentation, new is used when you need to control the creation of a new instance, while init is used when you need to control the initialization of a new instance.

new is the first step in creating an instance. It is called initially and is responsible for returning a new instance of your class.

In contrast, init does not return anything; it is only responsible for the initialization of the instance after it has been created.
Usage of new and init: The distinction between new and init is crucial.
new is typically used when you want to customize how an instance is created, whereas init is used for customizing the initialization process after the instance is created.

Returning Values: new should return an instance of the class, while init does not return anything. init is focused on setting up the initial state of the object.

Order of Execution: new is called first, followed by init. Understanding this order is important when working with class constructors.

Initialization Logic: init is the place to put code that sets up the object's initial state, such as initializing attributes or performing other setup tasks.

class MyClass:
    def __new__(cls, *args, **kwargs):
        # Custom logic for creating a new instance
        instance = super(MyClass, cls).__new__(cls)
        print("Creating a new instance")
        return instance

    def __init__(self, value):
        # Initialization logic after the instance is created
        self.value = value
        print("Initializing instance with value:", value)

# Creating an instance of MyClass
obj = MyClass(value=42)
Enter fullscreen mode Exit fullscreen mode

Output:
Creating a new instance
Initializing instance with value: 42

  1. Custom new Method: The new method is called first, and it should return an instance of the class. In this example, it prints a message and returns the instance.
  2. super().new(cls): It calls the new method of the parent class to ensure proper object creation.
  3. Custom init Method: The init method initializes the created instance. In this example, it sets the value attribute and prints a message.
  4. Usage of Constructor: The last line creates an instance of MyClass by passing a value of 42. This triggers both new and init methods.

If you need further information or have specific questions, feel free to ask! Tahsin Soyak tahsinsoyakk@gmail.com

Top comments (0)