In Python Destructor, a destructor is a special method called __del__()
that is automatically invoked when an object is about to be destroyed or garbage-collected. It allows you to define custom cleanup actions or release resources before the object is removed from memory.
Here’s an example that demonstrates the usage of a destructor in Python:
class MyClass: def __init__(self, name): self.name = name def __del__(self): print(f"Destructor called for {self.name}") # Create objects obj1 = MyClass("Object 1") obj2 = MyClass("Object 2") # Delete one of the objects del obj1 # Output: # Destructor called for Object 1 # Delete the remaining object del obj2 # Output: # Destructor called for Object 2
In the example above, the MyClass
class has a destructor __del__()
defined. When an object of MyClass
is deleted using the del
statement or when it goes out of scope and is garbage-collected, the destructor is automatically called.
In the destructor method, you can include any cleanup code or release resources associated with the object. In the example, the destructor simply prints a message indicating which object is being destroyed.
It’s important to note that the timing of the destructor’s invocation is determined by the garbage collector and may vary. Therefore, relying solely on the destructor to release resources is not recommended. It’s generally better to explicitly release resources or use context managers (with
statement) when dealing with external resources like files or network connections.
Additionally, it’s worth mentioning that the destructor is not guaranteed to be called for every object due to the reference-counting nature of Python’s garbage collector. Circular references or objects involved in reference cycles may not have their destructors called immediately. In such cases, the destructors are typically invoked when the cyclic garbage collector detects and collects those objects.