Python Constructor
A constructor is used to initialize a class when its instance is created. The first parameter of the constructor is always “self”. Constructor in Python is created using a special function known as __init__() function.
How to Create a constructor in Python?
A constructor in Python can be created using __init__() function that can take any number of parameters with self as a first parameter. Let us consider the following example to create an Employee class with three attributes, id, name, and department.
class Employee: def __init__(self, id, name, department): self.id = id self.name = name self.department = department def display(self): print("ID: %d \nName: %s\nDepartment: %s" % (self.id, self.name, self.department)) emp1 = Employee(1,"John Doe", "Web Development") emp2 = Employee(2,"Ryan Rees", "Mobile Development") emp1.display() emp2.display()
The output of the above program is:-
Name: John Doe
Department: Web Development
ID: 2
Name: Ryan Rees
Department: Mobile Development
class Student: def __init__(self): print("This is non parametrized constructor") def show(self, name): print("Hello", name) student = Student() student.show("John Snow")
Output:-
Hello John Snow