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.
Constructor types | |
Default Constructor | Parameterized constructor |
This is a default constructor where no arguments are accepted.
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. 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: number variable: 1001
|
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 : Id value : 101 name_value : Terry age_value : 27 gender_value : male doj_value : 10072015 dob_value : 10071993
|
How Does Constructor Work?
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
- __Init__() function
- Self Reference
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 Program
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 :
runfile(‘C:/Users/Dell/.spyder-py3/temp.py’, wdir=’C:/Users/Dell/.spyder-py3′)
Enter Name of the student: Arun
Enter the age of the student: 15
Enter the gender of the student: male
Class of the student: 11
Evaluated Marks per subject :
Mark in Literature subject: 45
Mark in Math subject: 34
Mark in Biology subject: 23
Mark in Physics subject: 45
Enter Name of the student: Rajan
Enter the age of the student: 16
Enter the gender of the student: male
Class of the student: 11
Evaluated Marks per subject :
Mark in Literature subject: 23
Mark in Math subject: 34
Mark in Biology subject: 23
Mark in Physics subject: 56
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
This is a guide to Constructor in Python. Here we discuss the Constructor Types and How does the Constructor in Python works. You may also look at the following article to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses