Python Constructor

A constructor is a special method that is used to initialize the instance variables of a class.

In the constructor, we create the instance variables and initialize them with some starting values. The first parameter of the constructor will be 'self' variable that contains the memory address of the instance.

Constructor syntax:

CopiedCopy Code

def __init__(self): 
   self.name = 'Vishnu' 
   self.marks = 900  

For example, If we see above code the formal arguments are 'n' and 'm' whose default values are given as ' ' (None) and 0 (zero).

Hence, if we do not pass any values to constructor at the time of creating an instance, the default values of these formal arguments are stored into name and marks variables.

s1 = Student('Lakshmi Bai', 880)

In this case, we are passing two actual arguments: 'Lakshmi Bai' and 880 to the Student instance. Hence these values are sent to the arguments 'n' and 'm' and from there stored into name and marks variables.

Mutiple python constructor

CopiedCopy Code

class Student: 
#this is constructor. 
   def __init__(self, n ='', m=0): 
      self.name = n 
      self.marks = m 
#this is an instance method. 
   def display(self): 
      print('Hi', self.name) 
      print('Your marks', self.marks) 
#constructor is called without any arguments 
s = Student() 
s.display() 
print('------------------') 
#constructor is called with 2 arguments 
s1 = Student('Lakshmi Bai', 880) 
s1.display() 
print('------------------')