A constructor is a method which is called when an object is created. In Python the constructor method can be written with keyword “__init__()” Every line of code inside the __init__ method will be execute at the time of object creation For Example.
class Employee: company = 'google' def __init__(self): print('New Employee Object is created')
So, this is the method of defining a constructor, you have noticed that in __init__ function we also have passed a parameter with name of self this is the default parameter of every method defined inside the class. So, why we used it. The self keyword pointing to the current object of this class like other languages we use this keyword self is almost similar to this keyword in other programming languages. But in python it should be first parameter of every method otherwise interpreter will give an error.
Note: It is also not necessary to use only self keyword as first parameter but you can also use any other keyword in replace of self but this keyword will point to current object. In most cases every developer is using self keyword because of better readability of code.
So, when we create an object of above given code Like
john = Employee()
Now when we run the code it will print New Employee Object is created because this print statement is inside the constructor method.
Parameters to constructor
We can also pass other parameters to constructor and use them inside the constructor and that code will be executed at the time of object creation For Example:
class Employee: company = 'google' def __init__(self, name, age): self.name = name self.age = age john = Employee('John', 20) print(john.name) print(john.age) print(john.company)
In above given code we also put 2 more parameters to constructor method, and inside the method we used self.name so what its means that this is creating a new property called name and getting the value from parameter name and assigning it to property. So, self is pointing to current object and doing work for current object .
when we create an object of this class we only pass parameters name & age and ignore the first parameter self which is default parameter of method and every method inside class always have this method so when we execute the this code it will create 2 more properties called name & age and object creation and than we print all the properties by accessing them with object name and it will print result like this.
John #This is the Employee name which is set in constructor 20 #This is the Employee age which is also set in constructor google #This is the Employee company name which is class default property