Table of contents
1.
Introduction
2.
Difference Between Constructor and Destructor
3.
What is a Constructor?
3.1.
Syntax of Constructor
3.2.
Example of Constructor
4.
What is a Destructor?
4.1.
Syntax of Destructor
4.2.
Example of Destructor
5.
Example of Constructor and Destructor Together
6.
Frequently Asked Questions
6.1.
What happens if I don’t define a constructor in a class?
6.2.
Can a class have multiple constructors in Python?
6.3.
When is the destructor called in Python?
7.
Conclusion
Last Updated: Mar 17, 2025
Easy

Constructor and Destructor in Python

Author Sinki Kumari
0 upvote

Introduction

In Python, a constructor is a special method (__init__()) that gets called when an object is created, initializing the attributes of a class. A destructor (__del__()) is called when an object is deleted or goes out of scope, handling cleanup operations like closing files or releasing resources. 

Constructor and Destructor in Python

In this article, we will discuss constructors and destructors in Python, their significance, and examples demonstrating their implementation.

Difference Between Constructor and Destructor

ParametersConstructorDestructor
PurposeInitializes an object when it is createdCleans up the object before it is destroyed
Method Name__init__()__del__()
ExecutionCalled automatically when an object is createdCalled automatically when an object is deleted
ArgumentsCan take arguments to initialize variablesDoes not take arguments
Use CaseUsed to set up an object’s propertiesUsed to release resources like files or memory

What is a Constructor?

A constructor is a special method in a Python class that gets executed when a new object of the class is created. The constructor method is named __init__(). It is primarily used to initialize instance variables.

Syntax of Constructor

class ClassName:
    def __init__(self, parameters):
        # Initialize instance variables

Example of Constructor

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print("Student object created!")
    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")
# Creating an object of Student class
student1 = Student("Alice", 20)
student1.display()
You can also try this code with Online Python Compiler
Run Code

 

Output:

Student object created!
Name: Alice, Age: 20


Explanation:

  • The __init__() method initializes name and age.
     
  • When student1 is created, __init__() runs automatically and prints "Student object created!".
     
  • The display() method shows the student's details.

What is a Destructor?

A destructor is a special method in Python that is executed when an object is deleted. It is used to free resources, such as closing files or database connections. The destructor method is named __del__().

Syntax of Destructor

class ClassName:
    def __del__(self):
        # Code to execute when the object is destroyed

Example of Destructor

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print("Student object created!")
    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")
    def __del__(self):
        print("Student object destroyed!")
# Creating an object
student1 = Student("Alice", 20)
student1.display()
# Deleting the object
del student1
You can also try this code with Online Python Compiler
Run Code


Output:

Student object created!
Name: Alice, Age: 20
Student object destroyed!

 

Explanation:

  • The __del__() method executes when the object is deleted.
     
  • The del student1 statement explicitly destroys student1, triggering __del__().
     
  • This ensures proper resource cleanup when objects are no longer needed.

Example of Constructor and Destructor Together

Below is an example demonstrating both a constructor and a destructor in a Python class:

class FileHandler:
    def __init__(self, filename, mode):
        self.file = open(filename, mode)
        print("File opened successfully.")
    def write_data(self, data):
        self.file.write(data)
        print("Data written to file.")
    def __del__(self):
        self.file.close()
        print("File closed successfully.")
# Creating an object
file = FileHandler("sample.txt", "w")
file.write_data("Hello, Python!")
# Deleting the object
del file
You can also try this code with Online Python Compiler
Run Code


Output:

File opened successfully.
Data written to file.
File closed successfully.

 

Explanation:

  • The constructor (__init__()) opens a file for writing.
     
  • The write_data() method writes data to the file.
     
  • The destructor (__del__()) ensures the file is closed when the object is deleted.

Frequently Asked Questions

What happens if I don’t define a constructor in a class?

If a constructor is not defined, Python provides a default constructor that does nothing. However, you won’t be able to initialize instance variables unless explicitly set in another method.

Can a class have multiple constructors in Python?

Python does not support multiple constructors directly. However, you can use default arguments or class methods to achieve similar behavior.

When is the destructor called in Python?

The destructor is called when an object goes out of scope or is deleted using the del keyword. However, Python’s garbage collector may delay calling the destructor in some cases.

Conclusion

In this article, we learned about constructors and destructors in Python. Constructors initialize object attributes when an instance is created, while destructors clean up resources when an object is deleted. Understanding these concepts helps in managing memory efficiently and structuring object-oriented programs effectively.

Live masterclass