Constructor and Destructor in Python
Constructor is the special function that is
automatically executed when an object of a class is created. In Python, there
is a special function called “init”
which act as a Constructor. It must begin and end with double underscore. This
function will act as an ordinary function; but only difference is, it is
executed automatically when the object is created. This constructor function
can be defined with or without arguments. This method is used to initialize the
class variables.
General format of __init__ method
(Constructor function)
def __init__(self, [args ……..]):
<statements>
class Sample:
def __init__(self, num):
print("Constructor of class
Sample...")
self.num=num
print("The value is :",
num)
S=Sample(10)
The above class “Sample”, has only a
constructor with one argument named as num.
When the constructor gets executed, first the
print statement, prints the “Constructor of class
Sample….”, then, the passing value to the
constructor is assigned to self.num and finally itprints the value passed along
with the given string.
The above constructor gets executed
automatically, when an object S is
created with actual parameter 10. Thus, the Python display the following
output.
Constructor of class Sample...
The value is : 10
Class variable defined within constructor keep
count of number of objects created with the class.
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var
print("The object value is =
", var)
print("The count of object
created = ", Sample.num)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
In the above program, class variable num is shared by all three objects of
the class Sample. It is initialized to zero and each time an object is created,
the num is incremented by
Since, the variable shared by all objects,
change made to num by one object is reflected in other objects as well. Thus
the above program produces the output given below.
Output
The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3
Note: class variable is similar to static
type in C++
Destructor is also a special method gets
executed automatically when an object exit from the scope. It is just opposite
to constructor. In Python, __del__( ) method is used as destructor.
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var
print("The object value is =
", var)
print("The value of class
variable is= ", Sample.num)
def __del__(self):
Sample.num-=1
print("Object with value %d
is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.