A constructor is a distinct kind of approach (function) which is used to initialize the occasion participants of the class.
In C++ or Java, the constructor has the identical identify as its class, however it treats constructor in a different way in Python. It is used to create an object.
Constructors can be of two types.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is completed when we create the object of this class. Constructors also verify that there are sufficient assets for the object to function any start-up task.
Creating the constructor in python
In Python, the technique the __init__() simulates the constructor of the class. This method is known as when the classification is instantiated. It accepts the self-keyword as a first argument which permits gaining access to the attributes or technique of the class.
We can omit any number of arguments at the time of developing the type object, relying upon the __init__() definition. It is commonly used to initialize the class attributes. Every category should have a constructor, even if it definitely relies on the default constructor.
Consider the following example to initialize the Employee class attributes.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Counting the number of objects of a class
The constructor is referred to as mechanically when we create the object of the class. Consider the following example.
Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
Output:
The number of students: 3
Python Non-Parameterized Constructor
The non-parameterized constructor makes use of when we do not want to manipulate the value or the constructor that has only self as an argument. Consider the following example.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters alongside with the self. Consider the following example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Output:
This is parametrized constructor
Hello John
Python Default Constructor
When we do now not include the constructor in the class or neglect to declare it, then that becomes the default constructor. It does now not perform any venture however initializes the objects. Consider the following example.
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Output:
101 Joseph
More than One Constructor in Single class
Let’s have a seem at any other scenario, what occur if we declare the two identical constructors in the class.
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
The Second Constructor
In the above code, the object st known as the 2nd constructor whereas both have the equal configuration. The first method is not accessible by means of the st object. Internally, the object of the category will always name the last constructor if the type has a couple of constructors.
Note: The constructor overloading is now not allowed in Python.
Python built-in class functions
The built-in features described in the classification are described in the following table.
SN | Function | Description |
---|---|---|
1 | getattr(obj,name,default) | It is used to access the attribute of the object. |
2 | setattr(obj, name,value) | It is used to set a particular value to the specific attribute of an object. |
3 | delattr(obj, name) | It is used to delete a specific attribute. |
4 | hasattr(obj, name) | It returns true if the object contains some specific attribute. |
Example
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print(s.age)
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a Python category also incorporates some built-in classification attributes which grant information about the class.
The built-in classification attributes are given in the below table.
SN | Attribute | Description |
---|---|---|
1 | __dict__ | It provides the dictionary containing the information about the class namespace. |
2 | __doc__ | It contains a string which has the class documentation |
3 | __name__ | It is used to access the class name. |
4 | __module__ | It is used to access the module in which, this class is defined. |
5 | __bases__ | It contains a tuple including all base classes. |
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Leave a Review