Constructor and destructor in python

Python supports object-oriented programming, and the class constructor and destructor play a major role in objected oriented programming. 

The class keyword is used in object-oriented programming in Python. Once we've created a class, we can begin creating new objects or instances of the class, which is an effective method to reuse functionality in your code.

What is a constructor?

A constructor is generally used to instantiate an object. A constructor is automatically executed when the object of the class is created. A constructor is created with a magic function known as __init__. The function can be defined with or without an argument.  

The general syntax for the __init__ constructor is as follows:

def __init__(self, optional argument):        

Let's illustrate how a constructor works:

class name():
def __init__(self):
print("My name is Deborah")
a = name()

According to the code, we created a class named name. The class has only one constructor without no argument. The above constructor is executed immediately when the object a is created. 

Thus the code will print out "My name is Deborah".

Let's create a constructor with an argument.

class name():
def __init__(self, a):
self.a = a
print(f"My name is {a}")
b = name("Williams")

According to the code, we created a class named name. The class has only one constructor with a single argument, a. When the constructor gets executed, it will first print the statement, “My name is {variable}", then, the passing value to the constructor is assigned to self. a and finally it prints the value passed along with the given string. 

The code is automatically executed just by creating an object(b) with the required parameter.

Thus the output of the code is "My name is Williams".

What is a destructor?

Destructors are called when an object gets destroyed. The __del__() function is used as the destructor function in Python. 

The syntax of the destructor can be represented as follows:

def __del__():
#body of the code

Let's illustrate how the destructor works with a code.

class Player():
    def __init__(self):
        print('Player created.')
    def __del__(self):
        print('Player deleted.')
obj = Player()
del obj

According to the code, we declared a class named Player. Then, we instantiated the object with the constructor. The __del__ destructor is declared. An object was created as obj. Finally, by using the del keyword we deleted all references of object ‘obj’, therefore destructor invoked automatically. 



The constructor is executed when an object is created and destructors are called when an object gets destroyed. The destructor requires one to call the del keyword before the reference of the object is destroyed..