Hello friends how are you, today in this blog i will teach you what is constructor, types of constructor , how constructor works and many programs using constructor in a very simple way.
Let's start
Constructor
1.It 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.
- Parameterized Constructor
- 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("Aayushi",305) """ ***Output*** Name: Aayushi Rollno: 305 """
- 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 .
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all.
If you have not subscribed my website then please subscribe my website.
Try to learn something new and teach something new to other. Thanks.
0 Comments