Constructor

 

Constructor

Constructor is a special method that is invoked automatically when instance is created. It is used to initialize the instance variable with some default value. The first parameter of constructor is self that suggest that it refer to the current instance. The self-variable store the current instance address.

The default constructor example is written below:

def __init__(self):

self.id=1

self.name="abc"

Here, there is only one parameter self and this constructor is used to initiliaze it with some default value.

It is invoked automatically when we write,

e1=emp()

if we want to pass certain parameter at the time of instance creation the syntax of constructor is explained in following example.

Example:

class emp:

def __init__(self,id1=1,name1='abc'):

self.id=id1

self.name=name1

def printdata(self):

print("Emp id is",self.id)

print("Emp name is",self.name)


e1=emp()

e1.printdata()

e2=emp(2,"def");

e2.printdata()