Constructors
A constructor is a special type of method (function) which is used to initialize the instance members of the class.
Constructors can be of two types.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.
Creating a Constructor
Example 1:
ID: 101
Name: John
ID: 102
Name: David
Example 2: Counting the number of objects of a class
Class Attribute (count = 0) will be updated to (count = 3) because constructor (Student.count) is called 3 times
Print(Student.count) will return 3 as Class Attribute is updated to count = 3
Print(s1.count) will return 3 as self.count is not present in constructor. So, s1.count will also pick value from class attribute (count=3). But if self.count would have been present here, then s1.count would have picked value of self.count
The number of students: 3
Example 3:
In this example, when instance attribute self.count is not assigned any value, it will automatically pick value from class attribute, count=5
Student.count will not be updated as self.count is called in constructor, self.count result will reflect when called via objects s1, s2.
The number of students: 5
The number of students: 6
The number of students: 6
Example 4:
In this example, when self.count is assigned a value self.count = 2, it will not pick value from class attribute (count = 15)
The number of students: 15
The number of students: 3
The number of students: 3
Example 5:
110
110
The number of students: 112
The number of students: 111
Example 6:
The number of students: kukubird
Example 7:
The number of students: kukukukukukubird
Non-Parameterized Constructor:
Example 8:
This is non parameterized constructor
Hello John
Parameterized Constructor:
This is parameterized constructor
Hello John
Last updated