- 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:
def __init__(self,name,rollno,marks):
self.name=name
self.rollno=rollno
self.marks=marks
Program to demonistrate Constructor will execute only once per Object:
self.name=name
self.rollno=rollno
self.marks=marks
Program to demonistrate Constructor will execute only once per Object:
class Test:
def __init__(self):
print("Constructor exeuction...")
def m1(self):
print("Method execution...")
t1=Test()
t2=Test()
t3=Test()
t1.m1()
Output:def __init__(self):
print("Constructor exeuction...")
def m1(self):
print("Method execution...")
t1=Test()
t2=Test()
t3=Test()
t1.m1()
Constructor exeuction...
Constructor exeuction...
Constructor exeuction...
Method execution...
0 comments:
Post a Comment