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. 

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Data Science Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks