0% found this document useful (0 votes)
2 views

Constructor

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Constructor

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Self variable:

self is the default variable which is always pointing to current object (like this
keyword in Java)
By using self we can access instance variables and instance methods of object.
Note:
1. self should be first parameter inside constructor
def __init__(self):
2. self should be first parameter inside instance methods
def talk(self):
Constructor Concept:
Constructor is a special method in python.
The name of the constructor should be __init__(self)
Constructor will be executed automatically at the time of object creation.
The main purpose of constructor is to declare and initialize instance variables.
Per object constructor will be exeucted only once.
Constructor can take atleast one argument(atleast self)
Constructor is optional and if we are not providing any constructor then python
will provide
default constructor.
Example:
1) def __init__(self,name,rollno,marks):
2) self.name=name
3) self.rollno=rollno
4) self.marks=marks
Program to demonistrate constructor will execute only once per object:
1) class Test:
2)
3) def __init__(self):
4) print("Constructor exeuction...")
5)
6) def m1(self):
7) print("Method execution...")
8)
9) t1=Test()
10) t2=Test()
11) t3=Test()
12) t1.m1()
Program:
1) class Student:
2)
3)
4) def __init__(self,x,y,z):
5) self.name=x
6) self.rollno=y
7) self.marks=z
8)
9) def display(self):
10) print("Student Name:{}\nRollno:{} \nMarks:
{}".format(self.name,self.rollno,self.marks)
)
11)
12) s1=Student("amol",101,80)
13) s1.display()
14) s2=Student("Sunny",102,100)
15) s2.display()
Differences between Methods and Constructors:
Method Constructor
1. Name of method can be any name 1. Constructor name should be always __init__
2. Method will be executed if we call that
method
2. Constructor will be executed automatically at
the time of object creation.
3. Per object, method can be called any number
of times.
3. Per object, Constructor will be executed only
once
4. Inside method we can write business logic 4. Inside Constructor we have to
declare and
initialize instance variables

You might also like