Skip to content

Constructor and destructor in Python | Basics

  • by

Python Constructor is the special function that is automatically executed when an object of a class is created. Python __init__ function is to act as a Constructor.

def __init__(self, [args ……..]):

<statements>

Python Destructor is also a special method that gets executed automatically when an object exit from the scope. In Python, __del__( ) method is used as the destructor.

Examples of Constructor and destructor in Python

Simple example code:

Python constructor is executed automatically when the object is created. This constructor function can have arguments.

class Sample:

    def __init__(self, num):
        print("Constructor of class Sample...")
        self.num = num
        print("The value is :", num)


S = Sample(100)

Output:

Constructor and destructor in Python

Example program to illustrate the del( ) method

class Sample:
    num = 0

    def __init__(self, var):
        Sample.num += 1
        self.var = var

        print("Object value is = ", var)
        print("Variable value = ", Sample.num)

    def __del__(self):
        Sample.num -= 1

        print("Object with value %d is exit from the scope" % self.var)


S1 = Sample(10)

Output:

Object value is = 10
Variable value = 1
Object with value 10 is exit from the scope

When is Constructor and destructor called in Python?

Answer: Constructor and destructor functions are automatically executed in Python. Constructor when an object of a class is created and Destructor when an object exit from the scope.

Do comment if you have any doubts or suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading