Updated April 18, 2023
Introduction to Python Constructors
Constructors in the Python programming language are used when the class’s object is created, along with verifying that there is a sufficient number of resources for the object to perform any sort of start-up task. A special type of function or method whose purpose is to initialize the members of the class and is generally characterized into two types. These functions are basically a Parameterized constructor and a Non-parametrized constructor. With the former working on the idea that parameters are taken into consideration, the latter believes it doesn’t require any parameter.
Types of Python Constructors
The key logic behind constructors is to ensure the initialization of instance members. In python to these constructors play the same typical role. In python, all the instance members can be initialized through these constructors.
1. Default Constructor
A default argument is present in the case of default constructors namely called self. This argument refers to the object being created for this class. This is a default constructor where no arguments are accepted.
Example:
class sample:
# default constructor
def __init__(self):
# initializing variable instance
self.number_variable=1001
# a method
def print_method(self):
print("number variable : ",self.number_variable)
obj=sample()
obj.print_method()
Output:
2. Parameterized constructor
Parameterized constructors accept arguments within them. Like default constructors here, too, the first argument being created references the instance of this class. The rest of the arguments are needed and defined by the programmer to reference the instance variables.
Example:
class sample:
# parameterized constructor
def __init__(self , id , name , age , gender, doj , dob ):
self.id_value = id
self.name_value = name
self.age_value = age
self.gender_value = gender
self.doj_value = doj
self.dob_value = dob
def print_output(self):
print("Id value :", self.id_value)
print("name_value :", self.name_value)
print("age_value :", self.age_value)
print("gender_value :", self.gender_value)
print("doj_value :", self.doj_value)
print("dob_value :", self.dob_value)
obj1=sample(101,'Terry',27,'male',10072015,10071993)
obj1.print_output()
Output:
How Does Constructor Work in Python?
When an object is created for a python class, then the constructor function will be the first code segment to be initiated for execution, and this makes all initializations happen as the first instance of work for the program. the two key elements in this process of constructors are as below
1. Init() Function
This function is called when the object instance for the corresponding class is created. This constructor function is affirmed using a def keyword which is dreadfully alike to all other function declarations. Another noticeable thing in these init function declaration in the function will be preceded and suffixed by double underscores.
Example
def __init__(self,salary_arg)
2. Self Reference
The self references the object itself. The self can refer to the functions and variables respective to the class within which it is involved. this has to be the foremost parameter in the constructor declaration. It signifies that the exponent is expected to work with the attributes of this object.
The method show also uses self as its keyword
Example
def __init__(self,Employee_name,Employee_id, Employee_age):
self.Employee_name = name;
self.Employee_id = id;
self.Employee_age = age
Example Of Constructors in Python
Program using Constructors Example.
#!/usr/bin/evn python
# Define a class as 'Individual' #
class Individual:
# Constructor#1 #
def __init__(self):
self.Student_Name = input( " Enter Name of the student : " )
self.Student_age = input( " Enter age of the student : " )
self.Student_gender = input( " Enter gender of the student : " )
# Method
def display(self):
print( " \n \n Enter Name of the student : " , self.Student_Name )
print( " Enter age of the student : " , self.Student_age )
print( " Enter gender of the student : " , self.Student_gender )
# Define a class as 'Evaluated_Marks' #
class Evaluated_Marks:
# Constructor#2 #
def __init__(self):
self.stuClass = input( " Class of the student : " )
print( " Evaluated Marks per subject : " )
self.literature = int(input( " Mark in Literature subject : " ))
self.math = int(input( " Mark in Math subject : " ))
self.biology = int(input( " Mark in Biology subject : " ))
self.physics = int(input( " Mark in Physics subject : " ))
# Method
def display(self):
print( " Study in : " ,self.stuClass)
print( " Total Evaluated_Marks : " , self.literature + self.math + self.biology + self.physics)
class student(Individual, Evaluated_Marks):
def __init__(self):
# Call ' Individual ' super class constructor
Individual.__init__(self)
# Call ' Evaluated_Marks ' super class constructor
Evaluated_Marks.__init__(self)
def result(self):
# Call method of class 'Individual'
Individual.display(self)
# Call method of class 'Evaluated_Marks'
Evaluated_Marks.display(self)
# Objects of class 'student' #
Student1 = student()
Student2 = student()
print(" ")
print( " Note : The instances get initialized with the given values Successfully " )
Output:
Advantages of Constructors
- The major advantage of constructors is they are largely helpful in initializing
- Instance variables in the final status can be set or initialized only using constructors.
- Default value initializations can be omitted using constructors
- when an object is created for a python class. The constructor function will be the first code segment to be initiated for execution, and this makes all initializations to happen as the first instance of work for the program.
- Constructors can be initiated with and without parameters
Conclusion – Constructor in Python
Constructors play a signifying role in every high-level programming language. Similar to like in the case of python, the responsibility of constructors is primarily in place when the concept of object-oriented programming is implied. Constructors help to achieve optimized instance variable initializations.
Recommended Articles
We hope that this EDUCBA information on “Constructor in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.