Constructor in Python

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 Garbage collection in python

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

Read Python if else with examples

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

Read Python For Loop with Examples

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

Read Python read excel file and Write to Excel 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

Read Create a tuple in Python

What is Garbage collection in python

  • Python garbage collection is the memory management mechanism.
  • In python, the memory allocation and deallocation methods are automatic.
  • Python deletes unwanted objects automatically to free up space.
  • The process in which python periodically frees and reclaims blocks of memory that no longer are in use is called garbage collection.
  • Python garbage collector runs during program execution and it is triggered when the object reference count reaches zero.
  • Python uses two strategies for memory allocation reference counting and garbage collection.

Reference Counting

  1. Reference counting is a simple technique in which objects are deallocated when there is no reference to them in a program.
  2. Reference counting works by counting the number of times an object is referenced by other objects in the system.
  3. When references to an object are removed then the reference count for an object is decremented.
  4. The reference count becomes zero, then the object is deallocated.

Example:

val = 10
val = 12
print(val)

After writing the above code (reference counting) the output will appear as a “ 12 “. Here, the reference count of object 10 will become 0 as it dereferenced. So the garbage collector deallocates the object.

You can refer to the below screenshot for reference counting.

Reference Counting
Reference Counting

Note: A reference cycle is created when there is no way the reference count of the object can reach. The easiest way to create a reference cycle is to create an object which refers to itself.

Automatic Garbage collection in python

The automatic garbage collection in python works automatically. When no reference is left to a variable or object then the memory occupied by that object is freed up by the garbage collection mechanism. Also, it provides good memory management and prevents memory wastage.

Example:

class Obj:
    def __init__(self):
        print('Object is created.')
    def __del__(self):
        print('Object is destroyed.')
obj1 = Obj()
obj2 = obj1
obj3 = obj1
print("Set obj1 to None")
obj1 = None
print("Set obj2 to None")
obj2 = None
print("Set obj3 to None")
obj3 = None
  • After writing the above code (automatic Garbage collection in python) the output will appear.
  • Here, the Obj is created which is referenced by obj1 and obj2, obj3 also refers to the same memory location.
  • After the creation of the object, the __init__() method is called, and when the object is destroyed due to garbage collection __del__() method is called.
  • When the variable is assigned to None then the reference from the object is removed.
  • When no reference is left to the object then it is automatically destroyed and __del__ method() is executed.

You can refer to the below screenshot for automatic Garbage collection in python.

Automatic Garbage collection in python
Automatic Garbage collection in python

Forced Garbage Collection in python

A user may need to do garbage collection for memory management explicitly to free up some memory. So, we will import gc module which allows explicit garbage collection. Garbage collection can be done forcibly by using the collect() function of gc module.

Example:

import gc
class Obj:
    def __del__(self):
        print('Object is destroyed.')
obj1 = Obj()
obj2 = obj1
obj1 = None
obj2 = None
for i in range(5):
    dic = {}
    dic[0] = dic
print('Collecting')
n = gc.collect()
print('Unreachable objects:', n)
  • After writing the above code (forced garbage collection in python) the output will appear.
  • Here, the Object is created and the Obj class is destroyed by an implicit garbage collector.
  • But the case is not the same for object dic which is a dictionary pointing itself again forming a cycle and cannot be destroyed.
  • So, to destroy the object created by the cycle we will use the collect()method.
  • And the collect() method runs garbage collection and destroys the unused objects which have reference count 0.
  • The collect method returns the number of unreachable objects. Unreachable objects mean the object which has a count of 0.

You can refer to the below screenshot for forced garbage collection in python.

Forced Garbage Collection in python
Forced Garbage Collection in python

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
  • What is Garbage collection in python