Multiple Constructors in Python

Multiple constructors are required when we want to have a different behavior of an object to perform the different actions on the object of a class.

The different behavior of an object can be achieved by providing the different parameters based on the type of parameters, number of parameters.

We can have a different behavior of an object and the multiple constructors by using concept of the positional arguments(*args).

Look at the below example to illustrate the behavior of multiple constructors using *args.

In the example when length of arguments it 1, it behaves like one constructor with one argument __init__(self, roll_number), similarly when length of arguments is 2 it behaves like the another constructor with 2 arguments __init__(self, roll_number, name).

Constructors in Python

Destructors in Python

Popular Posts

Author

  • Naveen Pandey Data Scientist Machine Learning Engineer

    Naveen Pandey has more than 2 years of experience in data science and machine learning. He is an experienced Machine Learning Engineer with a strong background in data analysis, natural language processing, and machine learning. Holding a Bachelor of Science in Information Technology from Sikkim Manipal University, he excels in leveraging cutting-edge technologies such as Large Language Models (LLMs), TensorFlow, PyTorch, and Hugging Face to develop innovative solutions.

    View all posts
Spread the knowledge
 
  

Join the Discussion

Your email will remain private. Fields with * are required.