Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconWhat is Constructor Overloading in Python? With Examples

What is Constructor Overloading in Python? With Examples

Last updated:
9th Jun, 2023
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
What is Constructor Overloading in Python? With Examples

Python is a user-friendly programming language that can be easily mastered by beginners. This programming language offers a wide range of community support which helps the programmers in exploring several ways of implementing the code. The standard libraries in Python and the modules contributed by the community forum have allowed endless possibilities, including Web and internet development, desktop GUIs, database access, Education, scientific and numeric applications, network programming, software development and programs to develop games. This open-source language is developed under OSI approved license. Hence, it can be used and distributed free of cost. The Python Software Foundation administers the license of Python.

Constructors in Python:

The main function of a Python constructor is to instantiate the objects. At the time of object creation, the class data members are assigned values or initialized with the help of constructors. The function _init_ is a constructor in Python. It is often called when a new object is created.

The Syntax for declaration of a Constructor is

Def _init_(self):

# constructor’s body

There are two types of constructors in Python. They are:

  • Default constructor
  • Parameterized constructor

Default constructor:

It is a simple constructor and does not accept any input parameters. The definition of default constructors has only one argument that refers to the instance that is being constructed. 

Parameterized constructor:

As indicated by the name, these constructors have parameters. The first argument of this type of constructors refers to the instance that is constructed and it is known as ‘self’. All other required arguments are specified by the programmer as inputs.

Check Out upGrad’s Data Science Courses 

Constructor Overloading in Python:

Construct overloading refers to a scenario of incorporating more number of constructors with a separate list of parameters such that each constructor is used to accomplish different tasks in the program. For example, there are four types of constructors in the Vector class. 

Python does not explicitly support multiple constructors. However, the use of multiple constructors in Python can be accomplished in several ways. If a programmer writes multiple _init_ methods for the same class, the most recently written _init_ function overwrites all other constructors.

What is a Clean, Pythonic Way to Have Multiple Constructors in Python?

Python follows the “Readability counts” principle and emphasizes a clean and Pythonic coding style. While there is no direct support for constructor overloading in Python, there are elegant approaches to achieve the desired functionality. One way is to use default argument values, which enable the creation of constructors with different argument sets while maintaining clarity and readability.

Why are Multiple constructors required in Python?

When the user has a need of performing different actions to instantiate a class, the requirement of multiple constructors pops up. This is helpful when different actions are to be performed by the class on different parameters. The class constructors in Python are structured to exhibit polymorphism in three different ways, as listed below:

  1. Constructor overloading based on arguments
  2. Invoking _init_ methods
  3. Use of the @classmethod decorator

Explore our Popular Data Science Courses

Constructor Overloading in Python based on Arguments:

In this method, the constructors are overloaded by performing necessary action after the conditions for the passed arguments are checked. Let us consider an example of passing a parameter to the Sample class.

  • The number’s square is the answer if the input parameter is an int. 
  • If the length of the parameter is more than 1, the arguments’ sum is shown as the answer. 

Calling Methods with _init_:

When an instance of a class is created, the class can have a single _init_ constructor that can perform any assigned task. This constructor can be modified to handle different functions and perform different tasks based on the parameter that is passed. Let us consider an example where the following calculations are performed.

  • If two arguments are passed, the expression is evaluated as x = a2 – b2 
  • If three arguments are passed, then the expression evaluated is y = a2 + b2 – c
  • If the number of arguments passed exceeds three, then add the squares of those numbers and divide the sum by the argument with the highest value.

Using the @classmethod Decorator:

In Python, we can define methods invoked on the class rather than an instance using the @classmethod decorator. Alternative constructors can be made Using this decorator that offers various methods of initialising objects.

How Can Python Provide Multiple Constructors?

We can use the @classmethod decorator or default argument values in Python to create several constructors. We may design constructors with various argument sets by implementing these strategies, providing flexibility in object construction.

Read our popular Data Science Articles

What does Python’s instantiating of classes mean?

In Python, generating objects or instances of a class is called instantiating classes. It entails calling the constructor for the object’s class, initialising its attributes, and preparing it for usage.

Python’s support for defining multiple class constructors is possible using the previous methods. We can offer different ways to instantiate and initialise class objects by including default argument values or the @classmethod decorator.

Simulating Numerous Class Constructors in Your Classes: 

Python constructor overload techniques can be used to imitate numerous class constructors. This increases the accessibility and adaptability of our classes by enabling us to construct objects with various initialization settings.

Multiple Approaches for Providing Multiple Class Constructors: 

Python provides several different strategies for delivering multiple class constructors. We have numerous ways to implement the necessary functionality, including method overloading, default parameter values, and the @classmethod decorator.

Exploring Numerous Constructors Within the Existing Classes: 

We can implement numerous constructors within our existing classes by examining the aforementioned methods. As a result, object customisation and instantiation are made more adaptable to accommodate changing requirements.

If you’d like to learn in-depth about method overriding in Python, we suggest you take up the 18-month Master of Science in Data Science. upGrad offers this course from IIIT Bangalore and Liverpool John Moore’s University. The course teaches you skills like Statistics, Predictive Analytics using Python, Machine Learning, Data Visualization, Big Data Analytics, and more. Students with a strong knowledge of concepts of Python are well-positioned to tackle subjects like Deep Learning, Natural Language Processing, Business Analytics, and Data Engineering. 

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Explore Free Courses

Suggested Blogs

Priority Queue in Data Structure: Characteristics, Types & Implementation
57468
Introduction The priority queue in the data structure is an extension of the “normal” queue. It is an abstract data type that contains a
Read More

by Rohit Sharma

15 Jul 2024

An Overview of Association Rule Mining & its Applications
142458
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or
Read More

by Abhinav Rai

13 Jul 2024

Data Mining Techniques & Tools: Types of Data, Methods, Applications [With Examples]
101688
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno
Read More

by Rohit Sharma

12 Jul 2024

17 Must Read Pandas Interview Questions & Answers [For Freshers & Experienced]
58119
Pandas is a BSD-licensed and open-source Python library offering high-performance, easy-to-use data structures, and data analysis tools. The full form
Read More

by Rohit Sharma

11 Jul 2024

Top 7 Data Types of Python | Python Data Types
99373
Data types are an essential concept in the python programming language. In Python, every value has its own python data type. The classification of dat
Read More

by Rohit Sharma

11 Jul 2024

What is Decision Tree in Data Mining? Types, Real World Examples & Applications
16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on
Read More

by Rohit Sharma

04 Jul 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
82806
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

04 Jul 2024

Most Common Binary Tree Interview Questions & Answers [For Freshers & Experienced]
10477
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par
Read More

by Rohit Sharma

03 Jul 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
70274
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

02 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon