Constructors In Python | FACE Prep

Constructors in Python are special methods that are defined inside a class. They are invoked when an object is created for the class. Keeping this in mind, let us move ahead and discuss the need for constructors.

 Why Do We Need Constructors?

Constructors are used for initializing the data members (variables and methods) of a class. They also verify whether there are enough variables and methods available for an object to perform a task defined in the class. Let us understand constructors better by creating one. 

How To Create Constructor In Python?

Similar to Functions, a constructor is defined with the keyword ‘def’ followed by a constructor name and colon as shown in the below syntax.

def __init()__(self):

A constructor always has the name ‘init’ and the name is prefixed, suffixed with a double underscore(__). The first parameter of the constructor must be ‘self’. This parameter is used to store the object passed from the main() method. In Python, we have two types of constructors.

 Types Of Constructors

The two types of constructors in Python are,

1) Default constructor
2) Parameterized constructor

Let us discuss them with examples.

 a) Default Constructor

The default constructor does not have any parameters other than ‘self’. It will not accept any arguments other than the object created for the class in which it is defined. Below is an example code.

class Employee:
    age = 0 #class variable 
    #default constructor used to initialize 'age' with the value 22
    def __init__(self):
        self.age = 22

#main() method

John = Employee() #creating object (John) for the class 'Employee'. Once the object is created, the Python interpreter calls the default constructor
print(John.age) #printing the value stored in the variable 'age' using the object 'John'
Output:
22

If the user did not define a constructor inside a class, then the Python interpreter implicitly defines a default constructor that does not do any operations. 

We can pass arguments while creating an object and those arguments get stored in a parameterized constructor. Next, let us see how this works.

 b) Parameterized Constructor

This constructor accepts and stores arguments passed from the main() method during object creation. Below is an example code.

class Employee:
    def __init__(self, age, salary):
        self.age1 = age
        self.salary1 = salary

#main() method
John = Employee(22, 20000)  #passing arguments to the parameterized constructor
print(John.age1) 
print(John.salary1)
Output:
22
20000

Here, the values 22 and 20000 are passed as the arguments during the object creation to the parameterized constructor defined inside the class ‘Employee’. These values get stored in the parameters ‘age’ and ‘salary’. Later, both the values get assigned to the variables ‘age1’ and ‘salary1’. 

We can also create another object for the same class and pass the arguments as shown below.

class Employee:
    def __init__(self, age, salary):
        self.age1 = age
        self.salary1 = salary

#main() method
John = Employee(22, 20000) 
Alex = Employee(30, 27000)
print("John age:", John.age1) 
print("John salary:", John.salary1)
print("Alex age:", Alex.age1) 
print("Alex salary:", Alex.salary1)
Output:
John age: 22
John salary: 20000
Alex age: 30
Alex salary: 27000

Instead of using print statements, we can use a method to print the values as shown below.

class Employee:
    def __init__(self, age, salary):
        self.age1 = age
        self.salary1 = salary
    #method to print 'age1' and 'salary1'
    def Emp_print(self):
        print("Age:", self.age1, "\nSalary:", self.salary1)

#main() method
John = Employee(22, 20000) 
John.Emp_print()  #calling the method named 'Emp_print' using the object 'John'
Output:
Age: 22 
Salary: 20000

Now that we understand how a constructor gets invoked when an object is created for a class. Similar to this, a method named Destructor gets invoked when an object is dereferenced from the memory. Let us discuss destructors in detail.

 Destructors

Destructors are also special methods that are used to perform final operations like closing files, closing database connections, cleaning up the buffer or cache, etc. This method gets invoked for the following two reasons.

  1. When we explicitly delete an object created for a class using the keyword ‘del’
  2. When an exception occurs in the __init__ method while initializing an object

Next, let us see how to create a destructor.

 How To Create Destructor In Python?

A destructor is defined with the keyword ‘def’ followed by the destructor name and colon as shown in the below syntax.

def __del()__(self):

A destructor always has a name ‘del’ and the name is prefixed and suffixed with a double underscore(__). The first parameter of the destructor must be self. This parameter is used to store the object passed from the main() method. Below is an example code for destructor.

class Employee:
    def __init__(self, age, salary):
        self.age1 = age
        self.salary1 = salary
    def __del__(self): #destructor
        print("Destructor called and the class 'Employee' deleted")

#main() method
John = Employee(22, 20000) 
print(John.age1)
print(John.salary1)
del John  #deleting the object 'John' and calling the destructor
Output:
22
20000
Destructor called and the class 'Employee' deleted

 Summary

To conclude, whenever a user creates an object for a class without arguments, the default constructor defined inside the class gets invoked and if the user creates the object with arguments, the parameterized constructor gets invoked. Suppose, if the user did not define any constructor inside the class, then the Python interpreter implicitly invokes the default constructor which does not perform any operations.