Python Constructor & Destructor

Python Constructor:

  • 1. It is a special function that is __init__( ).
  • 2. It is specifically used to initialize data or object.
  • 3. It executes automatically when an object is creating which is the main advantage.
  • 4. It never returns any value.
  • There are two types of constructors like 0-arg constructor and n-arg(parameterized) constructor.

0-arg Constructor:

The constructor taking no argument is known as 0-arg constructor.

Example:

class ConstructorExample1:
  	x=0
  	y=0;
    def __init__(self):      #0-arg constructor
	    self.x=100
	    self.y=200

	def show(self):
        print("x=",self.x)
        print("y=",self.y)

ob=ConstructorExample1()      #object declaration
ob.show()

Output:
x= 100
y= 200


n-arg(parameterized) constructor:

  • 1. The constructor taking parameters is known as parameterized constructor.
  • 2. In this context, instance variable equals local variable.

Example:

class ConstructorExample2:
	x=0
    y=0
    def __init__(self,p,q):      #parameterized constructor
    	self.x=p
        self.y=q
    def show(self):
    	print("x=",self.x)
        print("y=",self.y)
ob=ConstructorExample2(400,500)      #object declaration
ob.show()

Output:
x= 400
y= 500


Python destructor:

  • Like constructor, destructor is a special function that is __del__().
  • Python destructor is used to destroy the object and perform the final cleanup operation.
  • Though python have garbage collector to clean up the memory, but it is not just memory which is freed when an object is destroyed, it can be a lot of other resources like closing open files, closing database connections, cleaning buffer or cache etc. Hence we said the final clean up.

Example:

class Example:
	def __init__(self):             #constructor
		print("object created")

	def __del__(self):              #destructor
	    print("object destroyed")

obj=Example()        #object declaration 
del obj

Output:
object created
object destroyed


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext