Ways to Achieve Multiple Constructors in Python

Hello Programmers, today’s article is about multiple constructors in Python. Switching to Python from any other programming language has all advantages except when it comes to multiple constructors. Python does not support multiple constructors. However, Python offers some alternative ways to support multiple constructors. We will discuss some of those ways here. But before that, let me brief you about what is the need for multiple constructors in a program.

Multiple constructions help you to customize your class according to its parameters. Upon using a different number of parameters, different constructions can be triggered. Unlike other programming languages, Python has a different way of handling multiple parameters. We’ll have a look at each of them in detail.

Python Multiple Constructors And Its Needs:

Multiple constructors come into use when a defined class has to perform different functions. And on different parameters or instances of a class.

On writing the same method multiple times for a class, the last one overwrites all the previous constructors. Since multiple constructors do not work well with Python, the class constructors exhibit polymorphism. This method helps to replicate the multiple constructor feature in Python.

Different ways to get Multiple Constructors in Python are:

  • Constructor overloading based on arguments
  • Methods calling from __init__
  • @classmethod decorator

Python Constructor overloading based on arguments as Multiple Constructors:

Example:

class example: 
  
    # constructor overloading 
    # based on args 
    def __init__(self, *args): 
  
        # if args are more than 1 
        # sum of args 
        if len(args) > 1: 
            self.answer = 0
            for i in args: 
                self.answer += i 
  
        # if arg is an integer 
        # square the arg 
        elif isinstance(args[0], integer): 
            self.answer = args[0]*args[0] 
  
        # if arg is string 
        # Print with hello
        elif isinstance(args[0], str): 
            self.answer = "Hello! "+args[0]+"."
  
  
e1 = example(1, 2, 3, 6, 8) 
print("Sum of list :", e1.answer) 
  
e2 = example(6) 
print("Square of integer :", e2.answer) 
  
e3 = example("Programmers") 
print("String :", e3.answer) 

OUTPUT:

Sum of list : 20
Square of integer : 36
String : Hello! Programmers

Explanation:

In the above example, the answer is the instance variable of the class example. Its value differed in different instances inside the class based on arguments. A class can have multiple arguments. Therefore, *args is defined as a tuple that holds different arguments passed to it.

The arguments are accessible using an index. For instance, as in the integer and string case, since only one argument is passed, it is thus accessed as args[0]. For the sum, more than one argument passed to it is accessed by using a loop.

Python Methods calling from __init__ as Multiple Constructors:

Example:

class equations: 
  
  # single constructor to call other methods 
    def __init__(self, *abc): 
  
        # when 2 arguments are passed 
        if len(abc) == 2: 
            self.ans = self.eq1(abc) 
  
        # when 3 arguments are passed 
        elif len(abc) == 3: 
            self.ans = self.eq2(abc) 
  
        # when more than 3 arguments are passed 
        else: 
            self.ans = self.eq3(abc) 
  
     def eq1(self, args): 
        x = (args[0]*args[0])+(args[1]*args[1]) 
        return y 

    def eq2(self, args): 
        y = args[0]+args[1]-args[2] 
        return x 
  
    def eq3(self, args): 
        temp = 0
        for i in range(0, len(args)): 
            temp += args[i]*args[i] 
          
        temp = temp/5.0 
        z = temp 
        return z 
  
  
abc1 = equations(4, 2) 
abc2 = equations(4, 2, 3) 
abc3 = equations(1, 2, 3, 4, 5) 
  
print("equation 1 :", abc1.ans) 
print("equation 2 :", abc2.ans) 
print("equation 3 :", abc3.ans) 

Output:

equation 1 : 12
equation 2 : 17
equation 3 : 11.0

Explanation:

In this example, three equations performed in the instances of the class are equaton1 – x= a2 + b2 equation2 – y = a + b – c. Equation3 – z = sum of the square of arguments passed / 5.0.

equation1 is for two arguments. equation2 is for three, and equation 3 is for more than three.

Using a multi-constructor in Python, a class having one constructor __init__ is defined. It can perform any action on the creation of different class instances. Above all, in the above code, equations to be evaluated are written in different instances of the class. Above all, the __init__ constructor calls different methods to return the answer based on the number of arguments passed.

@classmethod decorator as Multiple Constructors:

Example:

class equations: 
  
    # basic constructor 
    def __init__(self, x): 
        self.ans = x 

    @classmethod
    def eq1(obj, args): 
        
      # create an object for the class to return 
        a = obj((args[0]*args[0])+(args[1]*args[1])
        return a 
 
    @classmethod
    def eq2(obj, args): 
        b = obj(args[0]+ args[1] - args[2]) 
        return b 
  
    @classmethod
    def eq3(obj, args): 
        temp = 0
  
        # square of each element 
        for i in range(0, len(args)): 
            temp += args[i]*args[i] 
  
        temp = temp/5.0 
        z = obj(temp) 
        return z 
  
  
li = [[4, 2], [4, 2, 3], [1, 2, 3, 4, 5]] 
i = 0
  
# loop to get input three times 
while i < 3: 
  
    input = li[i] 
  
    # no.of.arguments = 2 
    if len(input) == 2: 
        p = equations.eq1(input) 
        print("equation 1 :", p.ans) 
  
    # no.of.arguments = 3 
    elif len(input) == 3: 
        p = equations.eq1(input) 
        print("equation 2 :", p.ans) 
  
    # More than three arguments 
    else: 
        p = equations.eq3(input) 
        print("equation 3 :", p.ans) 
  
    #increment loop         
    i += 1

Output:

equation 1 : 12
equation 2 : 17
equation 3 : 11.0

Explanation:

Equations performed in the above example are: equaton1 – x= a2 + b2. Equation2 – y = a+ b – c. Similarly, Equation3 – z = sum of the square of arguments passed / 5.0.

When two arguments are passed, equation1 is evaluated. For three arguments, equation2 is performed. For more than three arguments, equation3 is evaluated.

Instances are not created for the above class initially. Similarly, class methods are defined to evaluate the various equations using the @classmethod decorator. Therefore, they are now called using class names. In addition, we create objects inside the class methods after evaluating the equations. Therefore, the instance variable returns the answer.

Must Read

Conclusion:

In conclusion, we can say Python cannot support using multiple constructors for a class. It allows different alternatives discussed above. However, constructor overloading and __init__ definition incur certain problems. Firstly, there is no clear indication of what is required while creating class instances. Also, different combinations of initializing a new instance by passing arguments exist. The best out of the three alternatives given is thus decorating with @classmethod decorators as multi-constructors.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments