A constructor is a method which is used for the purpose of initializing the variable or instance member of class.
Constructor in python is created by __init__() function with self keyword. The self keyword is used to access attributes and methods of classes.
Constructor is executed once we create the Object of class.
def __init__(self): # body of the constructor
How to create constructor in python?
In Python, the init() function is used for creating constructor. This method is named when the class is initialize. It accepts the self-keyword which allows you for accessing the attributes or method of the class .
Every class must have a constructor, means if we are not creating constructor in python class, then python will automatically create default constructor.
Consider the subsequent example to initialize the worker class attributes.
Example: Constructor implementation program
class Student: def __init__(self, name, id): self.name = name self.id = id def display(self): print("ID:Name:", (self.id, self.name)) stud1 = Student("John", 101) stud2 = Student("David", 102) stud1.display() #accessing class method display
What are the types of constructor in python?
There are three types of constructor in python Parameterized, Non-parameterized and default constructor.
- Parameterized Constructor – A constructor with parameter is known as parameterized Constructor.
- Non-parameterized Constructor- A constructor without parameter is know as Non-parameterized Constructor.
- Default Constructor- The automatically created constructor in python is called as Default constructor.
Example: Default Constructor implementation
class DefaultConstructor: # default constructor def __init__(self): self.message = "Hello World" # a method for printing data members def print_message(self): print(self.message) # creating object of the class obj = DefaultConstructor() # calling the instance method using the object obj obj.print_message()