Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Constructor & Destructor in Python

Constructor & Destructor in Python: 

Constructor & Destructor are an important concept of oops in Python. 

Constructor:  A constructor in Python is a special type of method which is used to initialize the instance members of the class. The task of constructors is to initialize and assign values to the data members of the class when an object of the class is created. 

Destructor: Destructor in Python is called when an object gets destroyed. In Python, destructors are not needed, because Python has a garbage collector that handles memory management automatically. 

Let’s Understand Constructor & Destructor in Python.

Constructor and Destructor in python

Constructor:

  • The __init__ method is similar to constructors in c++ and Java.
  • Constructors are used to initialize the object’s state.
  • The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. 

Synatx: 

class ClassName:
def __init__( self , variables...):
##body

Types of Constructor: 

  • default constructor: The default constructor is a simple constructor which doesn’t have any argument to pass. Its definition has only one argument which is a reference to the instance being constructed.
  • parameterized constructor: constructor which has parameters to pass is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self. 

Code #1:

#python Program
#Rishikesh 
#constructor 
#default Constructor 

class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        printself.str1) 
        print(‘In constructor’)
        

ob = A() 

Output:

PrepInsta
In constructor

Destructor:

  • The __del__ method is similar to destructor in c++ and Java.
  • Destructors are used to destroying the object’s state.

Syntax:

class ClassName:
def __del__( self ,):
##body
constructor and destructor in python

Code #2:

#python Program

#Rishikesh 

#destructor

class A(object): 

    def __init__(self): 

        self.str1 = ‘PrepInsta’

        print(‘Object Created’ , self.str1) 

    def __del__(self):

        print(‘DEstructor is called Manually’)



ob = A() 

del ob 

#ob1=A()

#destructor will be called automattically for ob1

Output: 

Object Created PrepInsta
DEstructor is called Manually
  • The destructor was called after the program ended.
  • It can be called Automatically as well as manually.
  • Object will be deleted at the end of the program.