Course contentsShow
← Python
Lesson 664 of 1,06010. Advanced Language FeaturesFree lesson

Managing Class Initialization with __init__

Learners will distinguish between the creation and initialization stages of a class object to perform post-construction setup and state configuration.

In this lesson, you will learn how to distinguish between the creation of an object and its initialization to master the lifecycle of your class instances.

While you have spent recent lessons exploring the powerful mechanics of metaclasses and __new__ for controlling the creation of an object, __init__ serves as the primary hook for initialization. It is vital to understand that by the time __init__(self) is called, the object has already been created in memory.

The Lifecycle Split

Think of class construction as a two-stage process:

  1. Creation (__new__): The allocator phase where the object is instantiated and the memory layout is finalized.
  2. Initialization (__init__): The configuration phase where the newly created "blank" object is populated with its specific state.

Because __new__ returns the object, __init__ receives that instance as self. This is the perfect place to perform post-construction setup, such as assigning initial attributes, validating configuration inputs, or setting up complex internal structures that depend on the existence of the object.

class DatabaseConnection:
    def __new__(cls, *args, **kwargs):
        # The object is created here
        instance = super().__new__(cls)
        print("Stage 1: Object created in memory.")
        return instance

    def __init__(self, uri):
        # The object is configured here
        self.uri = uri
        self.is_connected = False
        print(f"Stage 2: Initializing instance with URI {self.uri}")

# Usage
conn = DatabaseConnection("localhost:5432")

Why the Distinction Matters

If you try to perform complex state configuration inside __new__, you risk interfering with the immutable aspects of object creation (especially with fixed-size types or slots). By keeping logic focused on state assignment inside __init__, you ensure your code remains predictable and maintainable.

If you find yourself needing to modify the class structure itself or restrict instantiation, you return to your metaclass tools. However, for 99% of your state configuration needs, __init__ is the standard, readable, and idiomatic interface for completing an object's lifecycle.

Key Takeaway: Use __new__ to control how an object is created and __init__ to handle the configuration and setup of its internal state.