Constructor in Python
- A constructor is a function(method) which is used to initialize the members of the class.
- The constructor method is executed when an object is created.
__init__()
is the constructor method in Python.
Syntax
class A: def __init__(self): #body of the constructor
Types of constructors:
1. Non-Parameterized Constructor:
Non-Parameterized Constructor does not take any argument.
Example
class Data: def __init__(self): self.a=25 self.b=40 def add(self): self.c=self.a+self.b print("Total : ",self.c) obj=Data() obj.add()
Output
Total : 65
2. Parameterized Constructor:
Parameterized constructor takes at least one argument.
Example
class Data: def __init__(self,x,y): self.a=x self.b=y def add(self): self.c=self.a+self.b print("Total : ",self.c) obj=Data(50,60) obj.add() obj=Data(75,25) obj.add()
Output
Total : 110 Total : 100