Thursday, October 21, 2021

Constructors VS Destructors in Python

Difference between Constructors VS Destructors  in Python


What is Constructors in Python?

ANS:
#Constructors are generally used for instantiating an object.
#The task of constructors is to initialize(assign values) to the data members of the class
#when an object of class is created.
#In Python the __init__() method is called the constructor and is always called when an object is created.

#Syntax of constructor declaration :

#def __init__(self):
  # body of the constructor
#Types of constructors :

#1>default constructor :
#The default constructor is simple constructor which doesn’t accept any arguments.It’s definition has only one argument
#which is a reference to the instance being constructed.
#2>parameterized constructor :
#constructor with parameters is known as parameterized constructor.
#The parameterized constructor take its first argument as a reference to the instance being constructed known as self 
#and the rest of the arguments are provided by the programmer.
#python # #reference #oops#dataanalytics

What is Destructors in Python?

ANS:
#Destructors are called when an object gets destroyed. In Python, 
#destructors are not needed as much needed in C++ because Python has a garbage collector that handles memory management 
#automatically.
#The __del__() method is a known as a destructor method in Python. 
#It is called when all references to the object have been deleted i.e when an object is garbage collected.
#Syntax of destructor declaration :

#def __del__(self):
 # body of destructor
  #Here is the simple example of destructor.
#By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically.
#Generally, Python’s garbage collector which is used to detect these types of cyclic references would remove it
#but in this example the use of custom destructor marks this item as “uncollectable”.
#Simply, it doesn’t know the order in which to destroy the objects, \
#so it leaves them. Therefore, if your instances are involved in circular references they will live in the memory for as long as the application run.


No comments:

Post a Comment

"๐Ÿš€ Delta Lake's Vectorized Delete: The Secret to 10x Faster Data Operations!"

"๐Ÿš€ Delta Lake's Vectorized Delete: The Secret to 10x Faster Data Operations!" Big news for data engineers! Delta Lake 2.0+ in...