Constructors in Python

A constructor is a special type of function (method) which is used to initialize the members of the class

There are two types of constructors in python :
  • parametrized constructor 
  • non-parameterized constructor 
constructors are the functions which are executed when an object is cretead of the class.
constructors also verify that there are enough resources for the object to perform any start-up task

In simpler words constructor can be defined as a special function defined inside of class which is automatically called whenever an object is created of that class


non-Parametrized constructor:
  • non-parametrized constructor are those in which when you dont have to manipulate values ,i.e when you dont need to change the values whenever a different function is called .
 example:

class dev:
    
     def __init__(self): # make sure to leave space between def and first underscore

           print("non- parametrized constructor ")

     def show(self,name):   # function created
           print(name)

s1 = dev()
s1.show("kenye")

 output:

non-parametrized constructor
kenye


 parametrized constructor 

parametrized constructor are used when you have to change the values for every function then you need parametrized function

example:

class dev:

     def __init__(self,name,roll)

             self.name = name
              self.roll =  roll
              print("parametrized constructor")

    def  show(name,roll)
            print( name, roll )

    def gui(name,roll)
            print(name,roll)

 s1 = dev()
s1.show("kumar", 25) # calling function show and putting name and roll no in it

s1. gui("sharma",  65) # calling function for gui


 default constructor:

it is the default constructor of python when there is no need to define init the python creates a default constructor

example:

class soft:

     def show(self)
           print("defualt")

s1 = soft()

s1.show()



Thankyou!!

 

Comments