Course contentsShow
← Python
Lesson 447 of 1,0607. Object-Oriented ProgrammingFree lesson

Controlling Object Initialization and Lifecycle

Master the __new__ and __init__ methods to manage instance creation and the __del__ method to handle object destruction cleanup.

In this lesson, you will learn how to master the complete lifecycle of an object by controlling how it is created, initialized, and destroyed.

The Lifecycle Workflow

In Python, creating an object is a two-step process: creation and initialization.

  1. __new__ (The Creator): This is the first step. It is a static method responsible for actually creating the new instance and returning it. You rarely need to override this, but it is powerful if you need to control the creation process itself (such as in the Singleton pattern).
  2. __init__ (The Initializer): Once __new__ has returned an instance, Python calls __init__ to set the initial state (the attributes) of that instance. This is the constructor method you are already familiar with.
  3. __del__ (The Destroyer): Known as the destructor, this method is called when an object is about to be destroyed (when its reference count drops to zero). It is used for cleanup, such as closing file handles or network connections.

Seeing it in Action

Observe how these methods track the object’s life:

class LifecycleDemo:
    def __new__(cls, *args, **kwargs):
        print("1. Creating the instance")
        return super().__new__(cls)

    def __init__(self, name):
        print(f"2. Initializing {name}")
        self.name = name

    def __del__(self):
        print(f"3. Cleaning up {self.name}")

# Usage
obj = LifecycleDemo("PythonObject")
del obj  # Manually triggering the cleanup

When to use what?

Most of the time, you only need __init__ to set your object’s starting data. Use __new__ only when you need to influence the allocation of the object itself (rare for beginners). Use __del__ sparingly; while it seems like the perfect place for cleanup, Python’s garbage collector manages memory automatically, so __del__ should be reserved for releasing external resources that aren't managed by Python’s memory system.

Key Takeaway: While __init__ sets up your object's data, __new__ manages the object’s birth, and __del__ handles the graceful final cleanup of resources.