Constructors with examples in Python

Python Constructors: In this tutorial, we will learn about the constructors in Python, the types of constructors with the help of examples. By Yash Khandelwal Last updated : January 03, 2024

What are Python constructors?

The constructors are the special methods that are used to initialize the instance variables during object creation i.e., they are generally used for instantiating an object. The main task of a constructor is to provide default values to the data members of the class.

Constructor Creation

The __init__ method is used to create the constructor of the class. When we instantiate the class, we call this method. It is generally used when we initialize the class attributes. It is a must for a class to have the constructor, even if they rely on the default constructor.

Constructor Definition (Declaration)

Constructor is a method, so you need to use the def keyword to define it. While declaring the constructor one important thing is Constructor always has init and the word init is having two underscores (__) before and after it, Like __init__.

The following is the syntax to define/declare a constructor:

def __init__(self):
    # code of the constructor

Here, __init__ is used for the constructor to a class. The self parameter refers to the instance of the object (like, this in C++).

Constructor Example

class Addition:
    # Defininf a constructor
    def __init__(self):
        # with the help of self.xyz
        # we are initializing instance variable
        self.num1 = 1000
        self.num2 = 2000
        self.num3 = 3000

    def result(self):
        self.num = self.num1 + self.num2 + self.num3
        print("Output:", self.num)

# Here we create the object for call
# which calls the constructor
Sum = Addition()

# calling the instance method
# using the object Sum
Sum.result()

Output

Output: 6000

Types of Python constructors

There are mainly two types of constructors in Python programming language:

  1. Default constructor or Non-parameterized constructor
  2. Parameterized constructor

1. Default constructor or Non-parameterized constructor

The default constructor or non-parameterized constructor is a simple constructor without having any extra parameter except one which is a reference to the instance being constructed. In other words, we can say that this type of constructor does not accept any parameter to initialize the data members. The data members can be assigned with the default values in it.

We cannot create the object if we don’t have a constructor in our program. This is why when we do not declare the constructor in our program Python having the inbuilt feature it does it for us. We can also define our default constructor by using the following syntax,

def __init__(self):
    # Initialize the data members with 
    # the default values

Default constructor or Non-parameterized constructor example

class Addition:
    num1 = 0
    num2 = 0
    num3 = 0

    # default constructor
    def __init__(self):
        # assign any default value
        # Here, we're 10 as default values
        # for all data members
        self.num1 = self.num2 = self.num3 = 10

    # function to add these values
    def result(self):
        self.num = self.num1 + self.num2 + self.num3
        return self.num

# main code

# Here we create the object for Addition class
# which calls the constructor
Sum = Addition()

# calling the instance method
# using the object Sum
print("Sum of the numbers:", Sum.result())

Output

Sum of the numbers: 30

2. Parameterized constructor

When we declare a constructor in the way that accepts the arguments during the object creation these types of constructors are called the parameterized constructors. The first parameter of the parameterized constructor is the reference to the instance being constructed (self) and other parameters are to initialize the data members of the class.

Parameterized constructor example

class Student:
    # Defining a parameterized constructor having arguments
    def __init__(self, name, ids, college):
        print("This is a parmeterized costructor in python:")
        self.name = name
        self.ids = ids
        self.college = college

    def Display_Details(self):
        print("Student Details:")
        print("Student Name:", self.name)
        print("Student ids:", self.ids)
        print("Student college:", self.college)

# Here we create the object for call
# which calls the constructor
student = Student("Yash", 2023, "Kcc")

# calling the instance method
# using the object student
student.Display_Details()

Output

This is a parmeterized costructor in python:
Student Details:
Student Name: Yash
Student ids: 2023
Student college: Kcc

Advantages of Python constructors

The following are the advantages of using constructors in Python:

  • Constructors are used for initializing the data members of the class which is very useful to assign default and user-provided values to the data members during the object creation.
  • Constructors are very easy to implement in our code, you don't need to use any extra library or anything for this. Just define a constructor like a normal function.
  • Constructors are useful to increase the readability of the code and also separate the things like data members values initialization, file & other posts closing codes, etc.
  • Constructors are helpful to achieve the very important concept of OOPs which is encapsulation.

Disadvantages of Python constructors

The following are the disadvantages of using constructors in Python:

  • Using the constructors, we cannot achieve the function overloading. Constructor overloading is not supported.
  • There are limited functionalities with Constructors in comparison to other programming languages.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.