Advertisement

Constructors In Python | Destructor in Python | Difference Between Constructor and Destructor

What are Constructors in Python    


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


Constructor and Destructor in Python


Why Do We Need Constructors?


We use constructor 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/created in the class. Let us create a constructor for better understand.


How To Create Constructor In Python?


Like 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/argument 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


In Python, Constructors are of two types.

1) Default constructor

2) Parameterized constructor

Let us discuss these types of constructor in detail with examples.

a) Default Constructor

The default constructor only have "self" parameter. It does 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 27
def __init__(self): self.age = 27 #main() method
Ajab = Employee() #creating object (Ajab) for the class 'Employee'. Once the object is created, the Python interpreter calls the default constructor
print(Ajab.age) #printing the value stored in the variable 'age' using the object 'Ajab'
Output:
27

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

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


b) Parameterized Constructor

This constructor accepts/store 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
Ajab = Employee(27, 50000) #passing arguments to the parameterized constructor
print(Ajab.age1)
print(Ajab.salary1)
Output:
2750000

In this example, the values 27 and 50000 are passed as the arguments during the object creation to the parameterized constructor defined inside the class 'Employee'. These values get stored/kept in the parameters 'age' and 'salary'. Later, these value assigned to the variables 'age1' and 'salary1'.

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

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

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

Instead of using/calling 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
Aman = Employee(22, 20000)
Aman.Emp_print() #calling the method named 'Emp_print' using the object 'Aman'
Output:
Age: 22
Salary: 20000

Now that we understand how a constructor gets invoked/called when an object is created. Like this, a method named Destructor gets invoked/called when an object is dereferenced/deleted from the memory. Let us discuss destructors in detail.


Destructors


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

  1. When we explicitly/completely delete an object created for a class using the keyword 'del'.
  2. When an error 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" like constructor and other methods followed by the destructor name and colon (:) as shown in the below syntax.

def __del()__(self):

A destructor always/must has a name 'del' and the name is prefixed and suffixed with a double underscore(__). The first parameter of the destructor must be self like constructor. This parameter is used to store/kept the object passed from the main() method. This 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 Aman = Employee(22, 20000) print(Aman.age1) print(Aman.salary1) del Aman #deleting the object 'Aman' and calling the destructor Output: 22 20000
Destructor called and the class 'Employee' deleted


Summary


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


To learn about difference between interpreter and compiler click here

To learn how to write code in python click here


Post a Comment

0 Comments