Python Constructor: A Constructor is a special kind of method automatically called while creating an object. A Constructor is defined in the class, and we can use this method to initialize the basic attributes of the class.
Usually, the constructor has the same name as its class in Java or C++. However, we treat constructor in a different manner in Python.
Constructors can be classified into two different types:
- Parameterized Constructor
- Non-Parameterized Constructor
A Constructor is defined and executed when an object of the class is created. Constructors also help to verify that enough resources available for the object to execute any start-up activity.
Building Constructor in Python
Python provides the __init__() function that simulates the class constructor. We call the __init__() function while instantiating the class. The __init__() function accepts the ‘self’ keyword as its first argument, which provides access to the attributes and method of the class.
Moreover, we can pass multiple arguments while creating an object of the class, depending on the definition of the __init__() function. The function is usually used for initializing the attributes of the class. It is necessary to have a constructor for every class, even if it depends on the default constructor.
Let us consider the following example for initializing the Class attributes.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Student:
def __init__(self, full_name, roll_number):
self.roll = roll_number
self.fullname = full_name
def display_info(self):
print(“Roll Number:”, self.roll)
print(“Student’s Name: “, self.fullname)
student_1 = Student(“George”, 45)
student_2 = Student(“Gracey”, 42)
# accessing display_info() method to print student 1 information
student_1.display_info()
# accessing display_info() method to print student 2 information
student_2.display_info()
|
Output:
1
2
3
4
5
6
|
Roll Number: 45
Student‘s Name: George
Roll Number: 42
Student’s Name: Gracey
|
Explanation:
In the above snippet of code, we have defined a class Student and initialized some attributes such as full_name and roll_number using the __init__() function. We have then defined the display_info() method to print the details to the user. Later, we have created two objects, student_1 and student_2 and access the method to print the objects’ information.
Counting the number of objects of a Class
The Constructors are called automatically while creating the objects of the class. Let us consider the following example to count the number of objects of a Class.
Example:
1
2
3
4
5
6
7
8
9
10
11
|
class Employee:
count = 0
def __init__(self):
Employee.count = Employee.count + 1
employee_1 = Employee()
employee_2 = Employee()
employee_3 = Employee()
employee_4 = Employee()
print(“The Total number of Employees:”, Employee.count)
|
Output:
1
2
3
|
The Total number of Employees: 4
|
Explanation –
In the above snippet of code, we have defined a class called Employee. We have then initialized a constructor and create some objects such as employee_1, employee_2, employee_3, and employee_4 for the Employee Class. And at last, we have used the Employee.count to count the objects of the Employee class.
Non-Parameterized Constructor in Python
A Constructor is said to be Non-Parameterized if the constructor has only self as an argument or the user does not want to manipulate the value.
Let us consider the following example to understand the functioning of a Non-Parameterized Constructor in Python.
Example:
1
2
3
4
5
6
7
8
9
10
|
class Employee:
# Initializing Non-Parameterized Constructor
def __init__(self):
print(“This is the Non-Parameterized Constructor.”)
def display(self, fname, lname):
print(“Hello”, fname, lname)
employee = Employee()
employee.display(“John”, “Snow”)
|
Output:
1
2
3
4
|
This is the Non–Parameterized Constructor.
Hello John Snow
|
In the above snippet of code, we have defined a class called Employee and initialized a non-parameterized constructor using the __init__() function having only an attribute as self.
Then we have defined another method called display for displaying the name of an employee and create an object called employee for the Employee class and print the name of the employee.
Parameterized Constructor in Python
A Constructor is said to be Parameterized if the constructor has more than one parameter along with the self.
Let us consider the following example to understand the working of parameterized constructor in Python.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
|
class Employee:
def __init__(self, fname, lname):
print(“This is the Parameterized Constructor.”)
self.first = fname
self.last = lname
def display(self):
print(“Hello”, self.first, self.last)
employee = Employee(“John”, “Snow”)
employee.display()
# Initializing Parameterized Constructor
|
Output:
1
2
3
4
|
This is the Parameterized Constructor.
Hello John Snow
|
Explanation –
In the above code, we have defined a class called Employee and initialized a parameterized constructor using the __init__() function having a self, fname, lname as its attributes. Then, we have defined another method called display for displaying the name of an employee and create an object called employee for the Employee class and print the name of the employee.
What is Default Constructor in Python?
The Constructor is termed as default constructor if the developers do not insert the constructor in the class of or forget to declare one. The Default Constructor only initializes the objects but does not perform any activity.
Let us consider the following example to understand the very concept behind Python Default Constructor.
Example:
1
2
3
4
5
6
7
8
9
10
|
class Employee:
branchcode = 1204
fullname = “Carl Johnson”
def info(self):
print(“Branch Code:”, self.branchcode)
print(“Employee Name:”, self.fullname)
emp = Employee()
emp.info()
|
Output:
1
2
3
4
|
Branch Code: 1204
Employee Name: Carl Johnson
|
Explanation –
In the above snippet of code, we have defined a class called Employee. We have then created two different attributes and assigned them some values instead of defining them in the __init__() function. We have then created the info() method to print. Later we have created the emp object of the class Employee and print the details to the users.
Declaring Multiple Constructors in Single Class
We have already learned a lot about the constructors and understood the examples for the same. But what if we try declaring more than one similar constructor in the Class.
To understand this very concept, let us have a look at the following example.
Example:
1
2
3
4
5
6
7
8
9
10
|
class myClass:
# Declaring First Constructor
def __init__(self):
print(“This is the first Constructor.”)
# Declaring Second Constructor
def __init__(self):
print(“This is the second Constructor.”)
class_1 = myClass()
|
Output:
1
2
3
|
This is the second Constructor.
|
Explanation –
In the above snippet of code, we have defined a class called myClass and declare two constructors with the same configuration. We have then created the object called class_1, but it cannot access the first method. Internally, the class object will always call the last constructor if the class has more than one constructor.
Note: Python does not allow constructor overloading.
Some Built-in Class Functions in Python
Some of the built-in functions defined in the class are listed below:
S. No. | Class Function | Description |
1 | getattr(obj, name, default) | It is used for accessing the object’s attribute. |
2 | setattr(obj, name, value) | It is used for setting a specific value to an object’s specific attribute. |
3 | delattr(obj, name) | It is used for deleting a particular attribute. |
4 | hasattr(obj, name) | It returns Boolean Value for the object consist of some definite attribute. |
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Employee:
def __init__(self, fullname, branchcode, profession):
self.name = fullname
self.code = branchcode
self.prof = profession
emp = Employee(“George Arthur”, 1203, “Software Engineer”)
# printing the attribute name of the object emp
print(getattr(emp, ‘name’))
# resetting attribute code value to 1025
setattr(emp, ‘code’, 1205)
# printing the modified value of code
print(getattr(emp, ‘code’))
# returns true if the Employee comprises of the attribute with name prof
print(hasattr(emp, ‘prof’))
# deleting the attribute code
delattr(emp, ‘code’)
# returns an error as the attribute is deleted already
print(emp.code)
|
Output:
1
2
3
4
5
6
7
8
9
|
George Arthur
1205
True
Traceback (most recent call last):
File “D:\Python\construct.py”, line 26, in <module>
print(emp.code)
AttributeError: ‘Employee’ object has no attribute ‘code’
|
In the above program, we have defined a class called Employee with some attributes and create an object called emp of the Employee class. We have then used some built-in class functions to see their relative outputs.
Built-in Class attributes in Python
A Python class contains few built-in class attributes, in addition to the other attributes, providing details related to the class.
Some of them are list below:
S. No. | Attribute | Description |
1 | __dict__ | Provides dictionary consists of information related to the class namespace. |
2 | __doc__ | Contains string with class documentation. |
3 | __name__ | Used for accessing the name of the class. |
4 | __module__ | Used for accessing the module where the class is defined. |
5 | __bases__ | Contains a tuple with all base classes. |
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Employee:
def __init__(self, fullname, branchcode, profession):
self.name = fullname
self.code = branchcode
self.prof = profession
def details(self):
print(“Employee Name:”, self.name)
print(“Profession:”, self.prof)
print(“Branch Code:”, self.code)
emp = Employee(“Barney Stinson”, 10293, “Software Developer”)
print(emp.__doc__)
print(emp.__dict__)
print(emp.__module__)
|
Output:
1
2
3
4
5
|
None
{‘name’: ‘Barney Stinson’, ‘code’: 10293, ‘prof’: ‘Software Developer’}
__main__
|
Explanation –
In the above snippet of code, we have defined a class called Employee and added some attributes such as fullname, branchcode, and profession. We have then defined a method called details() to print the details to the user. After that, we have created an object called emp of the Employee class and used the built-in class attributes to see the result.