Skip to content

Constructor & Destructor in Python

Constructors in Python: Initializing Objects with Purpose

In object-oriented programming, a constructor is a special method used for initializing instances of a class. In Python, the constructor method is named init, and it is automatically called when an object is created from a class. Constructors play a crucial role in setting up the initial state of objects, allowing for proper initialization and configuration. Let’s explore the key aspects of constructors in Python.

What is a Constructor in Python?

A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is automatically called. It is used to initialize the object’s state. Constructors can also be used to perform any required initialization of the object before it is used. Constructors are not mandatory in Python, but they are used to initialize the state of an object.

How to Create a Constructor in Python?

In Python, the constructor method is named __init____init__. It is automatically called when an object is created from a class. The __init____init__ method is used to initialize the state of an object. The __init____init__ method is called the constructor method because it is called when an object is created.

constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python constructor.py
Name: John
Roll: 1
command
C:\Users\username>python constructor.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

What is the Use of a Constructor in Python?

Constructors are used to initialize the state of an object. They are used to set the initial values of the instance variables of an object. They are used to initialize the state in a better way. You can directly assign values to the instance variables of an object, but it is not a good practice. It is better to use a constructor to initialize the state of an object.

Initializing Instance Variables Directly

instance_variables.py
class Student:
    name
    age
 
student1 = Student()
student1.name = 'John'
student1.age = 20
print('Name:', student1.name)
print('Age:', student1.age)
instance_variables.py
class Student:
    name
    age
 
student1 = Student()
student1.name = 'John'
student1.age = 20
print('Name:', student1.name)
print('Age:', student1.age)

Output:

command
C:\Users\username>python instance_variables.py
Name: John
Age: 20
command
C:\Users\username>python instance_variables.py
Name: John
Age: 20

In the above example, we have created two instance variables named namename and ageage. We have initialized the namename and ageage variables to the namename and ageage values of the student1student1 object. We have printed the namename and ageage variables using the student1student1 object. The output shows that the namename and ageage variables are unique to the object.

Initializing Instance Variables Using a Constructor

constructor.py
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
student1 = Student('John', 20)
print('Name:', student1.name)
print('Age:', student1.age)
constructor.py
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
student1 = Student('John', 20)
print('Name:', student1.name)
print('Age:', student1.age)

Output:

command
C:\Users\username>python constructor.py
Name: John
Age: 20
command
C:\Users\username>python constructor.py
Name: John
Age: 20

In the above example, we have created two instance variables named namename and ageage. We have initialized the namename and ageage variables to the namename and ageage parameters of the __init__()__init__() method. We have printed the namename and ageage variables using the student1student1 object. The output shows that the namename and ageage variables are unique to the object.

How to Use a Constructor in Python?

In Python, the constructor method is named __init____init__. It is automatically called when an object is created from a class. The __init____init__ method is used to initialize the state of an object. The __init____init__ method is called the constructor method because it is called when an object is created. You need to pass the required parameters to the __init____init__ method when creating an object except the selfself parameter.

constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python constructor.py
Name: John
Roll: 1
command
C:\Users\username>python constructor.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Types of Constructors in Python

There are two types of constructors in Python:

  • Default Constructor: A default constructor is a constructor that does not take any parameters. It is used to initialize the instance variables of an object to their default values. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the default constructor because it is called when an object is created without any parameters.
  • Parameterized Constructor: A parameterized constructor is a constructor that takes one or more parameters. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the parameterized constructor because it is called when an object is created with parameters.

Default Constructor in Python

A default constructor is a constructor that does not take any parameters. It is used to initialize the instance variables of an object to their default values. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the default constructor because it is called when an object is created without any parameters.

default_constructor.py
class Student:
    def __init__(self):
        pass
 
student1 = Student()
default_constructor.py
class Student:
    def __init__(self):
        pass
 
student1 = Student()

In the above example, we have created a default constructor. It does not take any parameters. It is used to initialize the instance variables of an object to their default values. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the default constructor because it is called when an object is created without any parameters.

Another example of a default constructor:

default_constructor.py
class Student:
    def __init__(self):
        self.name = 'John'
        self.roll = 1
 
student1 = Student()
print('Name:', student1.name)
print('Roll:', student1.roll)
default_constructor.py
class Student:
    def __init__(self):
        self.name = 'John'
        self.roll = 1
 
student1 = Student()
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python default_constructor.py
Name: John
Roll: 1
command
C:\Users\username>python default_constructor.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll values of the student1student1 object. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Parameterized Constructor in Python

A parameterized constructor is a constructor that takes one or more parameters. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the parameterized constructor because it is called when an object is created with parameters.

parameterized_constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
parameterized_constructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python parameterized_constructor.py
Name: John
Roll: 1
command
C:\Users\username>python parameterized_constructor.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Another example of a parameterized constructor:

parameterized_constructor.py
class Employee:
    def __init__(self, name, salary, department):
        self.name = name
        self.salary = salary
        self.department = department
 
employee1 = Employee('John', 10000, 'IT')
print('Name:', employee1.name)
print('Salary:', employee1.salary)
print('Department:', employee1.department)
parameterized_constructor.py
class Employee:
    def __init__(self, name, salary, department):
        self.name = name
        self.salary = salary
        self.department = department
 
employee1 = Employee('John', 10000, 'IT')
print('Name:', employee1.name)
print('Salary:', employee1.salary)
print('Department:', employee1.department)

Output:

command
C:\Users\username>python parameterized_constructor.py
Name: John
Salary: 10000
Department: IT
command
C:\Users\username>python parameterized_constructor.py
Name: John
Salary: 10000
Department: IT

In the above example, we have created three instance variables named namename, salarysalary, and departmentdepartment. We have initialized the namename, salarysalary, and departmentdepartment variables to the namename, salarysalary, and departmentdepartment parameters of the __init__()__init__() method. We have printed the namename, salarysalary, and departmentdepartment variables using the employee1employee1 object. The output shows that the namename, salarysalary, and departmentdepartment variables are unique to the object.

Constructor with Default Parameters in Python

A constructor with default parameters is a constructor that takes one or more parameters with default values. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the constructor with default parameters because it is called when an object is created with default parameters.

constructor_with_default_parameters.py
class Student:
    def __init__(self, name='John', roll=1):
        self.name = name
        self.roll = roll
 
student1 = Student()
print('Name:', student1.name)
print('Roll:', student1.roll)
constructor_with_default_parameters.py
class Student:
    def __init__(self, name='John', roll=1):
        self.name = name
        self.roll = roll
 
student1 = Student()
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python constructor_with_default_parameters.py
Name: John
Roll: 1
command
C:\Users\username>python constructor_with_default_parameters.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Another example of a constructor with default parameters:

constructor_with_default_parameters.py
class Employee:
    def __init__(self, name='John', salary=10000, department='IT'):
        self.name = name
        self.salary = salary
        self.department = department
 
employee1 = Employee()
print('Name:', employee1.name)
print('Salary:', employee1.salary)
print('Department:', employee1.department)
constructor_with_default_parameters.py
class Employee:
    def __init__(self, name='John', salary=10000, department='IT'):
        self.name = name
        self.salary = salary
        self.department = department
 
employee1 = Employee()
print('Name:', employee1.name)
print('Salary:', employee1.salary)
print('Department:', employee1.department)

Output:

command
C:\Users\username>python constructor_with_default_parameters.py
Name: John
Salary: 10000
Department: IT
command
C:\Users\username>python constructor_with_default_parameters.py
Name: John
Salary: 10000
Department: IT

In the above example, we have created three instance variables named namename, salarysalary, and departmentdepartment. We have initialized the namename, salarysalary, and departmentdepartment variables to the namename, salarysalary, and departmentdepartment parameters of the __init__()__init__() method. We have printed the namename, salarysalary, and departmentdepartment variables using the employee1employee1 object. The output shows that the namename, salarysalary, and departmentdepartment variables are unique to the object.

Constructor with Default Parameters and Parameters in Python

A constructor with default parameters and parameters is a constructor that takes one or more parameters with default values and one or more parameters without default values. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the constructor with default parameters and parameters because it is called when an object is created with default parameters and parameters.

constructor_with_default_parameters_and_parameters.py
class Student:
    def __init__(self, name, roll, age=20):
        self.name = name
        self.roll = roll
        self.age = age
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)
constructor_with_default_parameters_and_parameters.py
class Student:
    def __init__(self, name, roll, age=20):
        self.name = name
        self.roll = roll
        self.age = age
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)

Output:

command
C:\Users\username>python constructor_with_default_parameters_and_parameters.py
Name: John
Roll: 1
Age: 20
command
C:\Users\username>python constructor_with_default_parameters_and_parameters.py
Name: John
Roll: 1
Age: 20

In the above example, we have created three instance variables named namename, rollroll, and ageage. We have initialized the namename, rollroll, and ageage variables to the namename, rollroll, and ageage parameters of the __init__()__init__() method. We have printed the namename, rollroll, and ageage variables using the student1student1 object. The output shows that the namename, rollroll, and ageage variables are unique to the object.

Constructor with keyword arguments in Python

A constructor with keyword arguments is a constructor that takes one or more parameters with default values and one or more parameters without default values. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the constructor with keyword arguments because it is called when an object is created with keyword arguments.

constructor_keyword_arguments.py
class Student:
    def __init__(self, name, roll, age=20):
        self.name = name
        self.roll = roll
        self.age = age
 
student1 = Student(name='John', roll=1)
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)
constructor_keyword_arguments.py
class Student:
    def __init__(self, name, roll, age=20):
        self.name = name
        self.roll = roll
        self.age = age
 
student1 = Student(name='John', roll=1)
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)

Output:

command
C:\Users\username>python constructor_keyword_arguments.py
Name: John
Roll: 1
Age: 20
command
C:\Users\username>python constructor_keyword_arguments.py
Name: John
Roll: 1
Age: 20

In the above example, we have created three instance variables named namename, rollroll, and ageage. We have initialized the namename, rollroll, and ageage variables to the namename, rollroll, and ageage parameters of the __init__()__init__() method. We have printed the namename, rollroll, and ageage variables using the student1student1 object. The output shows that the namename, rollroll, and ageage variables are unique to the object.

Constructor Overloading in Python

Constructor overloading is a technique in which a class can have more than one constructor. It is used to initialize the instance variables of an object to the values passed to the constructor. It is automatically called when an object is created from a class. It is used to initialize the state of an object. It is called the constructor overloading because it is called when an object is created with different parameters. You can create more than one constructor in a class. You can create a constructor with default parameters and parameters but constructor signature must be different.

constructor_overloading.py
class Student:
    def __init__(self):
        self.name = 'John'
        self.roll = 1
        print('Default Constructor')
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
        print('Constructor 1')
    def __init__(self, name, roll, age):
        self.name = name
        self.roll = roll
        self.age = age
        print('Constructor 2')
    def __init__(self, name, roll, age, department):
        self.name = name
        self.roll = roll
        self.age = age
        self.department = department
        print('Constructor 3')
 
student1 = Student()
student2 = Student('John', 1)
student3 = Student('John', 1, 20)
student4 = Student('John', 1, 20, 'IT')
constructor_overloading.py
class Student:
    def __init__(self):
        self.name = 'John'
        self.roll = 1
        print('Default Constructor')
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
        print('Constructor 1')
    def __init__(self, name, roll, age):
        self.name = name
        self.roll = roll
        self.age = age
        print('Constructor 2')
    def __init__(self, name, roll, age, department):
        self.name = name
        self.roll = roll
        self.age = age
        self.department = department
        print('Constructor 3')
 
student1 = Student()
student2 = Student('John', 1)
student3 = Student('John', 1, 20)
student4 = Student('John', 1, 20, 'IT')

Output:

command
C:\Users\username>python constructor_overloading.py
Default Constructor
Constructor 1
Constructor 2
Constructor 3
command
C:\Users\username>python constructor_overloading.py
Default Constructor
Constructor 1
Constructor 2
Constructor 3

In the above example, we have created four constructors. We have initialized the namename, rollroll, ageage, and departmentdepartment variables to the namename, rollroll, ageage, and departmentdepartment parameters of the __init__()__init__() method. We have printed the namename, rollroll, ageage, and departmentdepartment variables using the student1student1, student2student2, student3student3, and student4student4 objects. The output shows that the namename, rollroll, ageage, and departmentdepartment variables are unique to the object. In this example, we have created four constructors with different parameters. You can create more than one constructor in a class. You can create a constructor with default parameters and parameters but constructor signature must be different.

Constructor Chaining in Python

Constructor chaining is a technique in which a constructor calls another constructor of the same class. It is used to initialize the instance variables of an object to the values passed to the constructor.

constructor_chaining.py
class Student:
    def __init__(self, name, roll, age):
        self.name = name
        self.roll = roll
        self.age = age
    def __init__(self, name, roll, age, department):
        self(name, roll, age)
        self.department = department
 
student1 = Student('John', 1, 20, 'IT')
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)
print('Department:', student1.department)
constructor_chaining.py
class Student:
    def __init__(self, name, roll, age):
        self.name = name
        self.roll = roll
        self.age = age
    def __init__(self, name, roll, age, department):
        self(name, roll, age)
        self.department = department
 
student1 = Student('John', 1, 20, 'IT')
print('Name:', student1.name)
print('Roll:', student1.roll)
print('Age:', student1.age)
print('Department:', student1.department)

Output:

command
C:\Users\username>python constructor_chaining.py
Name: John
Roll: 1
Age: 20
Department: IT
command
C:\Users\username>python constructor_chaining.py
Name: John
Roll: 1
Age: 20
Department: IT

In the above example, we have created two instance variables named namename, rollroll, ageage, and departmentdepartment. We have initialized the namename, rollroll, ageage, and departmentdepartment variables to the namename, rollroll, ageage, and departmentdepartment parameters of the __init__()__init__() method. We have printed the namename, rollroll, ageage, and departmentdepartment variables using the student1student1 object. The output shows that the namename, rollroll, ageage, and departmentdepartment variables are unique to the object. In this example, we have created two constructors. We have initialized the namename, rollroll, and ageage variables to the namename, rollroll, and ageage parameters of the __init__()__init__() method. We have initialized the departmentdepartment variable to the departmentdepartment parameter of the __init__()__init__() method. We have called the first constructor from the second constructor using the self()self() method. We have passed the required parameters to the first constructor. We have passed the required parameters to the second constructor. We have printed the namename, rollroll, ageage, and departmentdepartment variables using the student1student1 object. The output shows that the namename, rollroll, ageage, and departmentdepartment variables are unique to the object.

Built-In Instance Methods in Python

There are many built-in instance methods in Python. The following table lists some of the most commonly used built-in instance methods in Python.

S.No.MethodDescription
1getattr()getattr()Returns the value of the specified attribute of an object.
2setattr()setattr()Sets the value of the specified attribute of an object.
3delattr()delattr()Deletes the specified attribute of an object.
4hasattr()hasattr()Returns TrueTrue if the specified attribute of an object exists, otherwise returns FalseFalse.

getattr()getattr() Method in Python

The getattr()getattr() method returns the value of the specified attribute of an object. It takes two parameters:

  • objectobject: The object whose attribute value you want to get.
  • namename: The name of the attribute whose value you want to get.
getattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', getattr(student1, 'name'))
print('Roll:', getattr(student1, 'roll'))
getattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', getattr(student1, 'name'))
print('Roll:', getattr(student1, 'roll'))

Output:

command
C:\Users\username>python getattr.py
Name: John
Roll: 1
command
C:\Users\username>python getattr.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the getattr()getattr() method. The output shows that the namename and rollroll variables are unique to the object.

setattr()setattr() Method in Python

The setattr()setattr() method sets the value of the specified attribute of an object. It takes three parameters:

  • objectobject: The object whose attribute value you want to set.
  • namename: The name of the attribute whose value you want to set.
  • valuevalue: The value of the attribute you want to set.
setattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
setattr(student1, 'name', 'John Doe')
setattr(student1, 'roll', 2)
print('Name:', student1.name)
print('Roll:', student1.roll)
setattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
setattr(student1, 'name', 'John Doe')
setattr(student1, 'roll', 2)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python setattr.py
Name: John Doe
Roll: 2
command
C:\Users\username>python setattr.py
Name: John Doe
Roll: 2

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have set the namename and rollroll variables using the setattr()setattr() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

delattr()delattr() Method in Python

The delattr()delattr() method deletes the specified attribute of an object. It takes two parameters:

  • objectobject: The object whose attribute you want to delete.
  • namename: The name of the attribute you want to delete.
delattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
delattr(student1, 'name')
delattr(student1, 'roll')
print('Name:', getattr(student1, 'name'))
print('Roll:', getattr(student1, 'roll'))
delattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
delattr(student1, 'name')
delattr(student1, 'roll')
print('Name:', getattr(student1, 'name'))
print('Roll:', getattr(student1, 'roll'))

Output:

command
C:\Users\username>python delattr.py
Traceback (most recent call last):
  File "delattr.py", line 9, in <module>
    print('Name:', getattr(student1, 'name'))
AttributeError: 'Student' object has no attribute 'name'
command
C:\Users\username>python delattr.py
Traceback (most recent call last):
  File "delattr.py", line 9, in <module>
    print('Name:', getattr(student1, 'name'))
AttributeError: 'Student' object has no attribute 'name'

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have deleted the namename and rollroll variables using the delattr()delattr() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

hasattr()hasattr() Method in Python

The hasattr()hasattr() method returns TrueTrue if the specified attribute of an object exists, otherwise returns FalseFalse. It takes two parameters:

  • objectobject: The object whose attribute you want to check.
  • namename: The name of the attribute you want to check.
hasattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', hasattr(student1, 'name'))
print('Roll:', hasattr(student1, 'roll'))
print('Age:', hasattr(student1, 'age'))
print('Department:', hasattr(student1, 'department'))
hasattr.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', hasattr(student1, 'name'))
print('Roll:', hasattr(student1, 'roll'))
print('Age:', hasattr(student1, 'age'))
print('Department:', hasattr(student1, 'department'))

Output:

command
C:\Users\username>python hasattr.py
Name: True
Roll: True
Age: False
Department: False
command
C:\Users\username>python hasattr.py
Name: True
Roll: True
Age: False
Department: False

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have checked the namename and rollroll variables using the hasattr()hasattr() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Destructor in Python

In object-oriented programming, a destructor is a special method used for destroying instances of a class. In Python, the destructor method is named __del____del__, and it is automatically called when an object is destroyed. Destructors play a crucial role in cleaning up the resources used by an object, allowing for proper cleanup and disposal. Let’s explore the key aspects of destructors in Python.

destructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
    def __del__(self):
        print('Destructor called')
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
destructor.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
    def __del__(self):
        print('Destructor called')
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python destructor.py
Name: John
Roll: 1
Destructor called
command
C:\Users\username>python destructor.py
Name: John
Roll: 1
Destructor called

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. We have created a destructor named __del____del__. We have printed the Destructor calledDestructor called message using the __del____del__ method. The output shows that the namename and rollroll variables are unique to the object. The output also shows that the Destructor calledDestructor called message is printed when the object is destroyed.

Usage of Destructors in Python

  • Destructors are used to destroy instances of a class.
  • Destructors are used to clean up the resources used by an object.
  • Destructors are used to perform any required cleanup before an object is destroyed.

Conclusion

In this tutorial, we have learned about constructors in Python. We have learned how to create a constructor in Python. We have learned what is the use of a constructor in Python. We have learned how to use a constructor in Python. We have learned how to create a constructor with parameters in Python. We have learned how to create a constructor without parameters in Python. We have learned how to create a default constructor in Python. We have learned how to create a parameterized constructor in Python. We have learned how to create a constructor with default parameters in Python. We have learned how to create a constructor with default parameters and parameters in Python. We have learned how to create a constructor with keyword arguments in Python. We have learned how to create constructor overloading in Python. We have learned how to create constructor chaining in Python. We have learned about built-in instance methods in Python. For more information on constructors in Python, see the official documentation. For more tutorials like this, check out Python Central Hub.

Was this page helpful?

Let us know how we did