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 of the 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.
Contents of Tutorial
Python Multiple Constructors And Its Need:
Multiple constructors come to 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.
Thus, 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:
class eaxmple: # 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, integer): self.answer = args*args # if arg is string # Print with hello elif isinstance(args, str): self.answer = "Hello! "+args+"." 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)
Sum of list : 20 Square of integer : 36 String : Hello! Programmers
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. While for the sum, more than one argument passed to it is accessed by using a loop.
Python Methods calling from __init__ as Multiple Constructors:
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*args)+(args*args) return y def eq2(self, args): y = args+args-args 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)
equation 1 : 12 equation 2 : 17 equation 3 : 11.0
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.
On passing two arguments, equation1 is evaluated. For three arguments, equation2 is performed. And for more than three arguments, equation3 is evaluated.
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:
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*args)+(args*args) return a @classmethod def eq2(obj, args): b = obj(args+ args - args) 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
equation 1 : 12 equation 2 : 17 equation 3 : 11.0
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. And 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 itself after the evaluation of the equations. Therefore the instance variable returns the answer.
- Introduction to Python Super With Examples
- Python Help Function
- Why is Python sys.exit better than other exit functions?
- Python Bitstring: Classes and Other Examples | Module
In conclusion, we can say, Python itself can not support the use of multi constructors for a class. It allows different alternatives discussed above. However, constructor overloading and __init__ definition incurs certain problems. Firstly, there is no clear indication of what is required while creating class instances. Also, there are different combinations of initializing a new instance by passing arguments. 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.