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

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905288
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20937
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5069
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5181
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17654
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10806
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80806
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

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
139155
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

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