All Courses

Constructors in Python: A Detailed Explanation

Pallavi Dhotre

2 years ago

Constructors in Python | insideAIML
Table of content 
Introduction
Constructor
  • The ‘self’
Types of constructors in python
  • Default Constructor
  • Parameterized Constructor
Destructor in Python
Multiple Constructors in Python
  • Constructor overloading based on the arguments
Summary

Introduction

          Learned about python classes and functions and want to know why do we need constructors? Constructor is a special member function in python. When the object of the class is created constructor gets automatically called. We need constructors to assign some initial values to the properties or attributes of the class. In this article, we will discuss constructors in python, types of constructors in python, constructor, and destructor in python, python constructor example, python multiple constructors, and constructor overloading in python. 

Constructor

          Constructor is a special member function provided by python. When the object of the class is created constructor automatically gets called. ‘__init__’ function in python is known as a constructor. Pay attention to two underscores (_) before and after ‘init’. If we don’t create our __init__ method, Python automatically creates one anyway (with no parameter). To know in-depth about constructors we need to deep dive into the ‘self’ keyword. 

The ‘self’

          From the scope of variables we know that we can access the variable only within the namespace they are created. 
  • A variable that is created inside the function has a local scope of that function and can only be used inside that function.
  • A variable created in the main body of the Python program can be accessed/used by all functions in the main program.
radious=10
def calculateArea():
    area=3.14*radious**2 #without using class
    print(area)
calculateArea()
2nd case is a little different while using a class. We use the ‘self’ keyword in the functions to access variables defined at the class level.
class circle:
    r=10 #variable declaration inside the class
    def calculateArea(self): 
        area=3.14*self.r**2  #accessing the variable using self-keyword
        print(area)
c=circle() #creating object
c.calculateArea() #calling function
Output
314.0
The important thing to remember about self: keyword ‘self’ is always the first parameter in each function of the class. If we want to access variables ‘r’ defined at the class level, we use ‘self. r’ 
‘self’ keyword in python has a special purpose and meaning. It is a reference to the object being created. Simply it works as a pointer to the object. 

Types of Constructors in Python

Default Constructor

          Python automatically invokes a default constructor. The ‘__init__’ function in python is a default constructor. We will see the example to understand how a constructor is called when an object is created. When we create an object of a class Python automatically
  • calls to  __init__ function internally. The __init__ function’s first parameter is the ‘self’ variable.
  • pass the reference (variable name of the object; c in this case) to the __init__ function. In other words, ‘self’ holds the reference to the object.
Example/ syntax of constructor in python:
class Demo:
    def __init__(self): #python constructor example
        a=40
        b=a/5
        print(b)
c=Demo()
Output: 
200
In this program, self-keyword passes the reference of object c to the __init__()function. 

Parameterized Constructor

          As we know that the default constructor is not of much use, we can create our constructor by passing the parameters in __init__ () function this constructor is also known as a parameterized constructor in python.
class Demo:
    def __init__(self,num1,num2): #parameterized constructor in python
        self.number1=num1
        self.number2=num2
    def add(self):
        return self.number1+self.number2
d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
Output
Addition of two numbers:  50
In this program __init__() function takes two additional parameters: num1 and num2. Since the constructor is still a function, once the execution of the function finishes, values of num1 and num2 will disappear. We must store these two values in the instance variables before they are gone. 

Destructor in Python

          When an object gets destroyed, the destructor is automatically called. __del__() method is also known as destructor in python. Once the program ends object gets destroyed. To know how to destroy objects visit the Python memory management article.
Let’s see the combined example of constructor and destructor in python
#constructor and destructor in python
class Demo:
    number1=10
    number2=20
    def __int__(self): #default constructor in python
        print("It is a default constructor")
    def __init__(self,num1,num2): #parameterized constructors in python
        self.number1=num1
        self.number2=num2
    def add(self):
        return self.number1+self.number2
    def __del__(self): #destructor in python
        print("It is a destructor")
d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
print("End of the program")
Output
Sum of two numbers:  50
End of the program
It is a destructor

Multiple Constructors in Python

          Using multiple constructors in python within the same class always overrides the previous constructors and displays the result of the constructor which is written at last. See the given code
class Demo:
    number1=10
    number2=20
    def __int__(self): #default constructor in python
        print("It is a default constructor")
    def __init__(self,num1,num2): #parameterized constructors in python
        self.number1=num1
        self.number2=num2
    def add(self):
        return self.number1+self.number2
    d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
Output
Sum of two numbers:  50
In this code, the second constructor is overriding the previous one. So this is not a useful way.
We can achieve the functionality of multiple constructors in python using the following ways:
  • by using constructor overloading based on the arguments
  • by calling the methods from the __init__() function
  • by using the decorator @classmethod
We will see constructor overloading based on the arguments in depth.

Constructor Overloading Based on The Arguments

          Multiple arguments can be passed to the single constructor by using *args.  See the following code
#constructor overloading in python / multiple constructors in python
class Demo:
    def __init__(self, *args):
    #more than one argument then multiplication
        if len(args)>1:
            self.result=1
            for i in args:
                self.result *=i
    #if the argument is a string then concat with hi
        elif isinstance(args[0],str):
            self.result= 'hi '+args[0]
    # if the argument is float the print square of a number
        elif isinstance(args[0],float):
            self.result =args[0]*args[0]

d1=Demo(2,3,4,5)
print("Multiplication of the list is ",d1.result)
d2=Demo("InsideAIML")
print("String concatenation is ",d2.result)
d3=Demo(2.5)
print("The Square of the float is ",d3.result)
Output
Multiplication of the list is  120

String concatenation is  hi InsideAIML

The Square of the float is  6.25

Summary

          In  this  article, we  discussed  constructors  in  python, types  of  constructor in python, default constructor in python, parameterized constructors in python, constructor and destructor in python, python constructor example, python multiple constructors, and constructor overloading in python. Constructor is a special member function in python. When the object of the class is created, the constructor gets automatically called. We need constructors to assign some initial values to the properties or attributes of the class. There are two types of constructors in python. The first is the default constructor and the second is the parameterized constructor. When the object of the class gets destroyed, the destructor automatically gets called. We hope you enjoyed the article. If you have any related queries, feel free to ask in the comment section below. 
   
Like the Blog, then Share it with your friends and colleagues to make this AI community stronger. 
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.
Keep Learning. Keep Growing.

Submit Review