Several init methods python

Ways to Achieve Multiple Constructors in Python

python multiple constructors

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.

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 Need:

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

Читайте также:  Вертикальное меню код css html

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:

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[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)
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]. 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[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)
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= a 2 + b 2 equation2 – y = a + b – c. Equation3 – z = sum of the square of arguments passed / 5.0.

Читайте также:  '.$obj->title.'

equation1 is for two arguments. equation2 is for three and equation 3 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:

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
equation 1 : 12 equation 2 : 17 equation 3 : 11.0

EXPLANATION:

Equations performed in the above example are: equaton1 – x= a 2 + b 2 . 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.

Must Read

Conclusion:

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.

Happy Pythoning!

Источник

How to Implement Multiple Constructors For Class in Python?

Multiple Constructors in Python

In this tutorial, we will learn what is python constructors and how to get multiple constructors for class in python?

Before proceeding with the multiple constructors class you must know about python constructors and how to initialize in the class.

What is Constructors in Python?

A constructor is a special kind of method (function) that is used to initialize the instance of the class. Python considers the constructors differently but the C++ and Java declare the same name as the class.

There are two types of constructors:

When we create an object of this class, the constructor function will be run. Constructors also check if the object has sufficient resources to complete any startup tasks.

To create a constructor in python, we will use the __init__() function. When the class is created, this method is invoked. It takes the self keyword as a first parameter, allowing access to the class’s properties and methods.

Let’s see the example of python constructors in a class.

Class Constructor with No-Parameters

We can create a python constructor without any parameters to logging the data to keep the count number of instances of the class.

Let’s declare the constructor function with the __init__() function. See in the below example.

Output

Student Constructor
Student Name is Oliver and Phone is 1234567890

Hope you understand the python constructors and how to use them.

As you see in the above examples there are only one constructors and yes we can only create one constructor in a class…BUT if you could create multiple constructors in python class, isn’t it helpful for you to handle complex functionality in short?

Let’s get started with multiple constructors in the python class.

Create Multiple Constructors in Python Class

You can create multiple constructors in class and you can customize it according to the parameters. Constructors will be run based on the different number of parameters.

It helps when a specified class performs several functions based on various parameters.

Create Multiple Constructors with __init__() Function

As we learned above the __init__() function used to create constructors in the python class. It declares with the first parameter of a self keyword. The self keyword allows us to access the variables and functions of the class.

To create multiple constructors in the python class, we declare the __init__() function with argument. That argument will check which function has to execute.

It means the class will execute different functions based on that argument condition checking in the constructor function. See the example below.

Output

Equation 1 : 38
Equation 2 : -5
Equation 3 : 55

Create Multiple Constructors with Constructor Overloading

In this method, the constructor will overload again and again based on the arguments. Look at the example below.

Output

Square of integer: 64
Sum of list: 44
Hope you understand the Multiple Constructors.

Источник

How to Implement Multiple Constructors For Class in Python?

Multiple Constructors in Python

In this tutorial, we will learn what is python constructors and how to get multiple constructors for class in python?

Before proceeding with the multiple constructors class you must know about python constructors and how to initialize in the class.

What is Constructors in Python?

A constructor is a special kind of method (function) that is used to initialize the instance of the class. Python considers the constructors differently but the C++ and Java declare the same name as the class.

There are two types of constructors:

When we create an object of this class, the constructor function will be run. Constructors also check if the object has sufficient resources to complete any startup tasks.

To create a constructor in python, we will use the __init__() function. When the class is created, this method is invoked. It takes the self keyword as a first parameter, allowing access to the class’s properties and methods.

Let’s see the example of python constructors in a class.

Class Constructor with No-Parameters

We can create a python constructor without any parameters to logging the data to keep the count number of instances of the class.

Let’s declare the constructor function with the __init__() function. See in the below example.

Output

Student Constructor
Student Name is Oliver and Phone is 1234567890

Hope you understand the python constructors and how to use them.

As you see in the above examples there are only one constructors and yes we can only create one constructor in a class…BUT if you could create multiple constructors in python class, isn’t it helpful for you to handle complex functionality in short?

Let’s get started with multiple constructors in the python class.

Create Multiple Constructors in Python Class

You can create multiple constructors in class and you can customize it according to the parameters. Constructors will be run based on the different number of parameters.

It helps when a specified class performs several functions based on various parameters.

Create Multiple Constructors with __init__() Function

As we learned above the __init__() function used to create constructors in the python class. It declares with the first parameter of a self keyword. The self keyword allows us to access the variables and functions of the class.

To create multiple constructors in the python class, we declare the __init__() function with argument. That argument will check which function has to execute.

It means the class will execute different functions based on that argument condition checking in the constructor function. See the example below.

Output

Equation 1 : 38
Equation 2 : -5
Equation 3 : 55

Create Multiple Constructors with Constructor Overloading

In this method, the constructor will overload again and again based on the arguments. Look at the example below.

Output

Square of integer: 64
Sum of list: 44
Hope you understand the Multiple Constructors.

Источник

Оцените статью