In this tutorial we will learn about the class __del__ method in Python.
We learned about classes and objects in the Python - Classes and Objects tutorial. Feel free to check that out.
The __del__ method is a special method of a class.
It is also called the destructor method and it is called (invoked) when the instance (object) of the class is about to get destroyed.
We use the __del__ method to clean up resources like closing a file.
In the following Python program we are creating the __del__ method inside the Awesome class.
# some method
# the del method
print("Hello from the __del__ method.")
# object of the class
obj = Awesome()
# calling class method
The above code will print the following output.
Hello from the __del__ method.
Points to note!
We get the above output because when the code is about to end the class Awesome is no longer required and so, it is ready to be destroyed.
Before the class Awesome is destroyed the __del__ method is called automatically.
In Python, any unused objects (like built-in types or instances of the classes) are automatically deleted (removed) from memory when they are no longer in use.
This process of freeing and reclaiming unused memory space is called Garbage Collection.
The concept of Garbage Collection is common in langauges like Java, C#, Python etc.
In the following Python program we are creating a new file and writing some text in it. Then we are closing the file in the __del__ method.
Learn more about File Handling in this tutorial.
# the init method
def __init__(self, filename):
print("Inside the __init__ method.")
# open file
self.fobj = open(filename, "w")
def writeContent(self, data):
print("Inside the writeContent method.")
# write the data
# the del method
print("Inside the __del__ method.")
# close file
obj = Awesome("helloworld.txt")
On running the above code we will get the following output.
Inside the __init__ method.
Inside the writeContent method.
Inside the __del__ method.
Have fun learning :-)
Copyright © 2014 - 2023 DYclassroom. All rights reserved.