Constructor in Python programming | Hands on Coding

Constructor

1. constructor is a special member function of class that executes when we create the instance(object) of that class.in other word we can say that there is no need to call a constructor.
2.__init__ () method is used as a constructor in Python.
3.There are two types of constructor are used in Python.

  1. Parameterized Constructor
  2. Non-parameterized Constructor

  • The constructor with parameter is called Parameterized Constructor
  • It can contain a number of parameters inside the constructor and the value of parameters is passed at the time of creation of object of class.
#creating class
class Student:
    #creating parameterized constructor
    def __init__(self,name,roll):
        print("Name:", name)
        print("Rollno:",roll)
#creating object
s1=Student("Raju",304)
"""
***Output***
Name: Raju
Rollno: 304
"""
  • The constructor with no parameter is called Non-parameterized Constructor
  • This type of constructor is also called default constructor.
  • This type of constructor is automatically called when we create object of that class.
#creating class
class Student:
    #creating non-parameterized constructor
    def __init__(self):
        print("Hi I am non-parameterized constructor")
    def Info(self):
        print("Name:Aayushi")
        print("Rollno:305")
#creating object
s1=Student()
s1.Info()
"""
***Output***
Hi I am non-parameterized constructor
Name:Aayushi
Rollno:305
"""

Here in the above program we can see that non-parameterized constructor is called as object  of class is created .


If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thank you!!..