Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Blog Categories  Tips & Tricks Contact

HOME
PYTHON HOW TO IMPLEMENT MULTIPLE CONSTRUCTORS FOR CLASS IN PYTHON?
FOLLOW US
Stay updated via social channels

How to Implement Multiple Constructors


For Class in Python?
HOW TO
PYTHON

AMAN MEHRA
JUNE 26, 2021
LEAVE A COMMENT
Get New Post By Email

Tweet on Twitter
Share on Facebook
Name

Your email address

SUBSCRIBE

RECENT POSTS

How to Change Proceed to


Checkout Button Text in
WooCommerce?

How to Add Watermark to Image


Using PHP?

In this tutorial, we will learn what is python constructors and how to get multiple Most Useful PHP Array Functions
constructors for class in python?
How to Create Nested Functions in
Python?
Before proceeding with the multiple constructors class you must know about
How to Change Place Order Button
python constructors and how to initialize in the class.
Text in WooCommerce?

So Let’s get started.

CATEGORIES
Table of Contents How To
1
What is Constructors in Python?
Laravel
1.1
Class Constructor with No-Parameters
PHP
1.2
Class Constructor with Parameters
2
Create Multiple Constructors in Python Class Python

2.1
Create Multiple Constructors with __init__() Function ReactJS
2.2
Create Multiple Constructors with Constructor Overloading
WooCommerce

WordPress

What is Constructors in Python?

A constructor is a special kind of method (function) that is used to initialize the MOST VIEWED POSTS
instance of the class. Python considers the constructors differently but the C++
WooCommerce Remove Update
and Java declare the same name as the class. Cart Button and Make it
Automatically Update.
There are two types of constructors:
How to Redirect to Checkout After
Add to Cart?
Parameterized Constructor
How to Change Price of Specific
Non-parameterized Constructor
Product and Quantity in Cart?

When we create an object of this class, the constructor function will be run. Upload Multiple Featured Images
Constructors also check if the object has sufficient resources to complete any in a Post OR Page
startup tasks.
How can I Prevent SQL Injection in
PHP?
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.
TIPS & TRICKS

Let’s see the example of python constructors in a class. Get Query String Parameters From
URL in JavaScript

Class Constructor with No-Parameters BuddyPress Members Not


Showing Until Login

We can create a python constructor without any parameters to logging the data Check the Memory Consumed By
to keep the count number of instances of the class. Variables in Python

WooCommerce Redirect to
Let’s declare the constructor function with the __init__() function. See in Checkout
the below example.
How to Remove the WordPress
Login Error Shake Effect
1 class Student:
2
3 count = 0
4
5 def __init__(self):
6 print('Student Constructor')
7 Student.count += 1
8
9
10 s1 = Student()
11 s2 = Student()
12 s3 = Student()
13 print("Student Object Count =", Student.count)

Output

Student Constructor
Student Constructor
Student Object Count = 3

Class Constructor with Parameters

Create a class constructor with parameters to initialize the instance of the


variable of the class.

1 class Student:
2
3 def __init__(self, n, p):
4 print('Student Constructor')
5 self.name = n
6 self.phone = p
7
8
9 s = Student('Oliver', '1234567890')
10 print(f'Student Name is {s.name} and Phone is {s.phone}

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.

1 class Calculation:
2
3 def __init__(self, *abc):
4
5 if len(abc) == 4:
6 self.ans = self.sum(abc)
7
8 elif len(abc) == 3:
9 self.ans = self.sub(abc)
10
11 else:
12 self.ans = self.mul(abc)
13
14 def sum(self, args):
15 x = (args[0]+args[1]+args[2]*args[3])
16 return x
17
18 def sub(self, args):
19 y = args[0]-args[1]-args[2]
20 return y
21
22 def mul(self, args):
23 count = 0
24 for i in range(0, len(args)):
25 count += args[i]*args[i]
26
27 z = count
28 return z
29
30
31 eq1 = Calculation(8, 2, 7, 4)
32 eq2 = Calculation(5, 3, 7)
33 eq3 = Calculation(1, 2, 3, 4, 5)
34
35 print("Equation 1 :", eq1.ans)
36 print("Equation 2 :", eq2.ans)
37 print("Equation 3 :", eq3.ans)

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.

1 class Result:
2
3 def __init__(self, *args):
4
5 if len(args) > 1:
6 self.answer = 0
7 for i in args:
8 self.answer += i
9
10 elif isinstance(args[0], int):
11 self.answer = args[0]*args[0]
12
13 elif isinstance(args[0], str):
14 self.answer = "Hope you understand the "+arg
15
16
17 a1 = Result(1, 2, 13, 6, 8, 5, 9)
18 a2 = Result(8)
19 a3 = Result("Multiple Constructors")
20
21 print("Square of integer:", a2.answer)
22 print("Sum of list:", a1.answer)
23 print(a3.answer)

Output

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

__INIT__() CONSTRUCTOR MULTIPLE LINES CONSTRUCTORS


CONSTRUCTORS OVERLOADING MULTIPLE CONSTRUCTORS
MULTIPLE PYTHON CONSTRUCTORS NON-PARAMETERIZED CONSTRUCTOR
PARAMETERIZED CONSTRUCTOR PYTHON PYTHON CONSTRUCTOR MULTIPLE INHERITANCE
PYTHON CONSTRUCTOR OVERLOADING PYTHON CONSTRUCTORS
PYTHON SMART CONSTRUCTOR PYTHON3 PYTHON3 MULTIPLE CONSTRUCTORS

Tweet on Twitter
Share on Facebook

YOU MAY ALSO LIKE

How to Change Proceed to Checkout How to Add Watermark to Image


Button Text in WooCommerce? Using PHP?

How to Create Nested Functions in How to Change Place Order Button


Python? Text in WooCommerce?

How to Re-Order WordPress Posts By How to Add Title Attribute in


Custom Field? WordPress Menu?

ABOUT THE AUTHOR: AMAN MEHRA


Hey! I'm Aman Mehra and I'm a full-stack developer and have 5+
years of experience. I love coding and help to people with this blog.

LEAVE A REPLY

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

Comment

Name * Email * Website

Save my name, email, and website in this browser for the next time I comment.

POST COMMENT

ABOUT QUICK LINKS RECENT POSTS GET IN TOUCH

Your Blog Coach is the best site Blog How to Change Proceed to
Name
for finding the solution to any Checkout Button Text in
WordPress
issue related to coding and learn WooCommerce?
WooCommerce
Your email address
more cool stuff and tricks.
How to Add Watermark to Image
Contact Using PHP?
SUBSCRIBE
Most Useful PHP Array Functions

© 2020 Your Blog Coach Privacy Policy


Terms and Conditions
Sitemap

You might also like