Python Destructor

In this quick tutorial, you will learn about what is destructor, why to use destructor and how to use destructor in python with examples, step by step in very beginner friendly way.

In previous tutorial we have learned, what is constructor? It is used to initialized object means assigning attributes and methods of class to object. Assigning attributes and methods of class to object increase size of program, so to solve this problem destructor come into role.

What is a destructor in python?

Python destructor is used for destroying object of class in python which is created by constructor in python.

The __del__() function or method is known as destructor in python. This function destroy all the object created by constructor.

In python, destructor is not useful that much as compare to other high-level programming language because for handling memory management automatically, python has garbage collector.

Syntax: destructor

def __del__:
    #body of destructor

Example: Simple Destructor Program

class DestructorExample():
    def __init__(self):
        print("constructor created")
    def __del__(self):
        print("destructor created")

del d

Example: Calling destructor in the end of program

# Python program for destructor

class DestructorExample:

	# Initializing
	def __init__(self):
		print('Destructor created')

	# Calling destructor
	def __del__(self):
		print("Destructor Deleted")

def Create_obj():
	print('Creating Object...')
	obj = DestructorExample()
	print('function ended')
	return obj

print('Calling Create_obj() function...')
obj = Create_obj()
print('Program Ended...')


Question and Answer Related to destructor

What is difference between constructor and destructor?

The constructor is used for constructing a value means initializing the value where destructor is used for destroy the value or object of class created by constructor.

What is a destructor in python?


The destructor is an opposite of constructor used for destroying the object of the class that was initialized by the constructor method. The __del__() method in python is called as destructor.
class DestructorExample():
def init(self):
print(“constructor created”)
def del(self):
print(“destructor created”)
del d

What is the use of destructor?

The destructor in python is used for destroying the object of the class that was initialized by the constructor method.

Was this article helpful?

1 thought on “Python Destructor”

Leave a Comment