Constructors are for instantiating an object.The task of constructors is to initialize the data members of the class when an object of class is created. The __init__() method is called the constructor in Python and is always called when an object is created.
class Employee:
- def __init__(self,name,id):
- self.id = id;
- self.name = name;
- def display (self):
- print("ID: %d \nName: %s"%(self.id,self.name))
- emp1 = Employee("John",101)
- emp2 = Employee("David",102)
- emp1.display();
- emp2.display();
Output:
ID: 101
Name: John
ID: 102
Name: David
Hope this is helpful!
To know more join Master in Python programming course today.
Thanks!