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.
__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).__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.__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.