In this post I am going to describing how constructors in python behaves like in other programming languages e.g. C++, Java etc.
Constructor Definition:
Generally, a constructor is a method which has the same name as the class name and is used to initialize an object.
In python constructors are treated differently, the class name and the method name of the constructor are different and is only used to initialize the object.
Constructor Creation:
A constructor is created in python using the method __init__().This method is called when the class is instantiated and accepts self as the first argument used to access the methods and attributes of the class.
Let us see an example:
class ClassMy: def __init__(self, name, age): self.name=name self.age=age def display(self): print("Name: ",self.name) print("Age: ", self.age) c=ClassMy("LingarajTechHub",25) c.display()
In the above program the name and age are passed in the constructor which is initialized in the variables and displayed in the display function. Where c is the object of the class instantiated.
Output:
This is a very import concept to deal with in python as we dive deep into python the importance of constructor rises.
Here we come to the end of the discussion on constructors in python. Hope we were able to clear all your doubts.
If you like this post and wants to improve or rewrite please WhatsApp us.