Python
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.
__del__
methodThe __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.
# class
class Awesome:
# some method
def greetings(self):
print("Hello World!")
# the del method
def __del__(self):
print("Hello from the __del__ method.")
# object of the class
obj = Awesome()
# calling class method
obj.greetings()
The above code will print the following output.
Hello World!
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.
# class
class Awesome:
# the init method
def __init__(self, filename):
print("Inside the __init__ method.")
# open file
self.fobj = open(filename, "w")
# method
def writeContent(self, data):
print("Inside the writeContent method.")
# write the data
self.fobj.write(data)
# the del method
def __del__(self):
print("Inside the __del__ method.")
# close file
self.fobj.close()
# object
obj = Awesome("helloworld.txt")
obj.writeContent("Hello World")
On running the above code we will get the following output.
Inside the __init__ method.
Inside the writeContent method.
Inside the __del__ method.
ADVERTISEMENT