Learn Python Programming

Python – Constructor & Destructor


Constructor in python is implemented using the __init__ function. You can define parameters that will follow the self object.

Syntax:

class Testclass:
    def __init__(self):
        print("Constructor")

The destructor is defined using __del__(self). In the below example, the obj is created and manually deleted, therefore both message will be displayed. Destructor is called when the object is deleted.

Syntax:

class Testclass:

    def __del__(self):
        print("Destructor")

If you execute the both constructor and destructor.

class Testclass:
    def __init__(self):
        print("Constructor")

    def __del__(self):
        print("Destructor")


if __name__ == "__main__":
    obj = Testclass()
    del obj

#OUTPUT
Constructor
Destructor