Curriculum
In Python, the __del__
method is a special method that is used to define the behavior of an object when it is about to be deleted (garbage-collected) from memory. This method is called when the del
statement or the del()
function is used to delete an object of a class. The __del__
method can be used to perform any necessary cleanup or finalization operations before the object is deleted.
Here’s an example of how the __del__
method can be used in Python:
class MyClass: def __init__(self, name): self.name = name print(f"{self.name} created") def __del__(self): print(f"{self.name} deleted") obj1 = MyClass("Object 1") obj2 = MyClass("Object 2") del obj1 del obj2
In this example, we define a MyClass
class with an __init__
method that initializes an object with a name
attribute and prints a message to indicate that the object has been created. We also define a __del__
method that prints a message to indicate that the object is about to be deleted.
When we create two MyClass
objects obj1
and obj2
, the __init__
method is called for each object and the messages “Object 1 created” and “Object 2 created” are printed.
When we delete obj1
and obj2
using the del
statement, the __del__
method is called for each object and the messages “Object 1 deleted” and “Object 2 deleted” are printed.
Note that the __del__
method is not guaranteed to be called for an object when it is deleted, because Python’s garbage collection mechanism is non-deterministic. The __del__
method should not be relied upon to perform critical cleanup operations or to release resources such as file handles or network connections. It is generally better to use the with
statement or the try...finally
construct to ensure that resources are properly released when they are no longer needed.