Constructor in Python

By: On:

In this Python tutorial, we will discuss Constructor in Python, we will learn the concept with the help of examples.

  • What is a constructor in python?
  • How to create a constructor in python
  • Non-parameterized constructor in python
  • Parameterized constructor in python
  • Default constructor in python
  • Multiple constructors python
  • Destructors in python
  • Program to count the number of objects created in python
  • Python constructor overloading
  • Python constructor overriding
  • Python constructor inheritance
  • Python Constructor alternate

What is a constructor in python?

What is a constructor in Python? In python, constructor is used to initialize the instance members of the class, and also it is a special type of method. Python constructor is used to create an object. In python, there are two types of constructors.


  • Parameterized Constructor
  • Non-Parameterized Constructor

How to create a constructor in python

  • To create a constructor in Python, we can use the __init__ () method of a class.
  • This method is called when the class is initiated.
  • It takes the ” self “ keyword as a first argument which allows accessing the attributes of the class.

Example:

class Teacher:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def disp(self):
print("Name: %s\nsalary: %d " % (self.name, self.salary))
t1 = Teacher("Jack", 100000)
t1.disp()

After writing the above code (creating a constructor in python) the output will appear as a “ Name: Jack salary: 100000 ”. Here, the class is initialized and it has the attribute name and salary. Accessing the ” disp() “ method to print ” t1 “ information.

You can refer to the below screenshot to create a constructor in python.

How to create a constructor in python
How to create a constructor in python

Non-parameterized constructor in python

In the non-parameterized constructor in Python, we do not want to manipulate the value or the constructor and it has only self as an argument.


Example:

class Teacher:
def __init__(self):
print("Non-parameterized constructor")
def disp(self,name):
print("Welcome", name)
t1 = Teacher()
t1.disp("Jonny")
  • After writing the above code (non-parameterized constructor in python) the output will appear as a “ non-parameterized constructor Welcome Jonny ”.
  • Here, my constructor has only “self” as an argument and during object creation, it does not have an argument this is known as a non-parameterized constructor.

You can refer to the below screenshot for non-parameterized constructor in python.

Non-parameterized constructor in python
Non-parameterized constructor in python

Parameterized constructor in python

  • The parameterized constructor in Python, is the constructor with multiple parameters.
  • Declaring a constructor in such a way that it accepts the arguments during object creation, then this type of constructor is called as parameterized constructor.
  • It takes the first argument as a reference to the instance being constructed known as ” self “.

Example:

class Teacher:
def __init__(self, name):
print("Parameterized constructor")
self.name = name
def disp(self):
print("Welcome", self.name)
t1 = Teacher("Jack")
t1.disp()

After writing the above code (parameterized constructor in python) the output will appear as a “ Parameterized constructor Welcome Jack”. Here, the constructor is called immediately when the object of the class is created.

You can refer to the below screenshot for parameterized constructor in python.

Parameterized constructor in python
Parameterized constructor in python

Default constructor in python

  • A default constructor in Python, is a constructor when we don’t add the constructor in the class or sometimes we forget to declare it, then we can say it is a Default constructor.
  • Even if we don’t have a constructor still we can create an object for the class because there is a default constructor implicitly injected in python code.

Example:

class Teacher:
roll = 10
def disp(self):
print(self.roll)
t1 = Teacher()
t1.disp()

After writing the above code (default constructor in python) the output will appear as a “ 10 ”. Here, the default constructor doesn’t accept any argument but still, it initializes the object and prints the roll.

You can refer to the below screenshot for default constructor in python.

Default constructor in python
Default constructor in python

Multiple constructors python

To create multiple constructors in Python, in the same class then the init method which is defined at last will be considered as the main init method.

Example:

class Teacher:
def __init__(self):
print("First constructor")
def __init__(self):
print("Last constructor")
t1 = Teacher()
  • After writing the above code (multiple constructors in python) the output will appear as a “ Last constructor ”.
  • Here, the object “t1” called the “last constructor” whereas both init are the same.
  • The first is not accessible by the object as it always calls the last constructor if multiple constructors are there in a class.

You can refer to the below screenshot for multiple constructor in python.

Multiple constructors python
Multiple constructors python

Destructors in python

  • In python, destructor is used to destroy the object. In python, we have a also garbage collector to clean up memory.
  • The __del__ method is known as the destructor method in python.

Example:

class Teacher:
def __init__(self):
print('Constructor is called')
def __del__(self):
print('Destructor is called')
obj1 = Teacher()
  • After writing the above code (destructor in python) the output will appear as a “ Constructor is called Destructor is called ”. Here, the __del__ method act as a destructor.
  • The destructor is called when the program ended also the reference of the object gets deleted when the programs end.

You can refer to the below screenshot for destructor in python.

Destructors in python
Destructors in python

Program to count the number of objects created in python

To count the number of objects created we will make one class variable and one method and in the constructor method, the value will be incremented.

Example:

class Teacher:
count = 0
def __init__(self,name,age):
self.name = name
self.age = age
Teacher.count = Teacher.count + 1
def disp(self):
print(self.name, self.age)
t1 = Teacher('John',45)
t2 = Teacher('Simon',55)
t3 = Teacher('Angelica',52)
print("The number of objects created: ",Teacher.count)
  • After writing the above code (program to count the number of objects created in python) the output will appear as a “ The number of objects created: 3 ”.
  • In the constructor method, we increment the class variable “count” by one, and when the object of this class created then the constructor method invoked automatically and it increments the values.

You can refer to the below screenshot for program to count the number of objects created in python.

Program to count the number of objects created in python
Program to count the number of objects created in python

Python constructor overloading

Overloading a constructor in Python, is allowed for a class and it should be instantiated with a different number of parameters.

Example:

class Flowers:
def __init__(self, first_parameter1, second_parameter2 = None):
self.first_parameter1 = first_parameter1
self.second_parameter2 = second_parameter2
print(Flowers("rose").__dict__)
print(Flowers("rose", "tulips").__dict__)
  • After writing the above code (python constructor overloading) the output will appear as a “ {‘first_parameter1’: ‘rose’, ‘second_parameter2’ : None} {‘first_parameter1’: ‘rose’, ‘second_parameter2’: ‘tulips’}”.
  • Here, we will use the default argument for the __init__() method to overload a constructor. The instance of a class is created with different numbers of parameters.

You can refer to the below screenshot python constructor overloading.

Python constructor overloading
Python constructor overloading

Python constructor overriding

Python constructor overriding mean one method will overrides the other. The parent class and child class both have the constructor and the child will override the parent constructor.

Example:

class Mother:
def __init__(self):
self.money = 23000
print("This is mother class constructor")
def show(self):
print("Mother class instance method")
class Son(Mother):
def __init__(self):
self.money = 12500
print("This is Son class constructor")
def display(self):
print("Son class instance method")
s = Son()

After writing the above code (python constructor overriding) the output will appear as a “ This is Son class constructor”. Here, the child class constructor overrides the parent class constructor and it prints the message of the child class.

You can refer to the below screenshot python constructor overriding.

Python constructor overriding
Python constructor overriding

Python constructor inheritance

In python, the constructor of the parent class is available to the child class by default, then this is called constructor inheritance.

Example:

class Mother:
def __init__(self):
self.money = 23000
print("This is mother class constructor")
def show(self):
print("Mother class instance method")
class Son(Mother):
def display(self):
print("Son class instance method")
s = Son()

After writing the above code (python constructor inheritance) the output will appear as a “ This is mother class constructor”. Here, the child class inherits the parent class constructor, and the object is created for the child class but it will print the message of the parent class.

You can refer to the below screenshot python constructor inheritance.

Python constructor inheritance
Python constructor inheritance

Python Constructor alternate

In python, we use “@classmethod” decorator and it work good for the alternative constructor.

Example:

class Teacher:
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
def details(self):
return f"name is {self.name} age is {self.age} and salary is {self.salary} "
@classmethod
def from_string(cls,string):
new = string.split(",")
print(new)
return cls(new[0],new[1],new[2])
t1 = Teacher("akhil","35", 26000)
t2 = Teacher.from_string("naksh,38, 27000")
print(t2.age)

After writing the above code (python constructor alternate) the output will appear as a “ [‘naksh’, ’38’, ‘27000’] “. Here, the “@classmethod” is used as an alternate and it will return the list. The split method is used and the return cls() will add the value in the respective place when we create the object “t2”.

You can refer to the below screenshot python constructor alternate.

Python Constructor alternate
Python Constructor alternate

You may like the following Python tutorials:

In this tutorial, we learned about constructor in python and also we have seen how to use it with an example like:

  • What is a constructor in python?
  • How to create a constructor in python
  • Non-parameterized constructor in python
  • Parameterized constructor in python
  • Default constructor in python
  • Multiple constructors python
  • Destructors in python
  • Program to count the number of objects created in python
  • Python constructor overloading
  • Python constructor overriding
  • Python constructor inheritance
  • Python Constructor alternate

Leave a Comment