Monday, March 14, 2022

Using constructors and destructors with classes

As with any other OOP language, Python also has constructors and destructors, but the naming convention is different. The purpose of having constructors in a class is to initialize or assign values to the class- or instance-level attributes (mainly instance attributes) whenever an instance of a class is being created. In Python, the __init__method is known as the constructor and is always executed when a new instance is created. There are three types of constructors supported in Python, listed as follows:

• Default constructor: When we do not include any constructor (the __init__method) in a class or forget to declare it, then that class will use a default constructor that is empty. The constructor does nothing other than initialize the instance of a class.

• Non-parameterized constructor: This type of constructor does not take any arguments except a reference to the instance being created. The following code sample shows a non-parameterized constructor for a Name: class:

class Name:

#non-parameterized constructor

def __init__(self):

print("A new instance of Name class is \

created")

Since no arguments are passed with this constructor, we have limited functionality to add to it. For example, in our sample code, we sent a message to the console that a new instance has been created for the Name class

• Parameterized constructor: A parametrized constructor can take one or more arguments, and the state of the instance can be set as per the input arguments provided through the constructor method. The Name class will be updated with a parameterized constructor, as follows:

class Name:

#parameterized constructor

def __init__(self, first, last):

self.i_first = first

self.i_last = last

Destructors are the opposite of constructors—they are executed when an instance is deleted or destroyed. In Python, destructors are hardly used because Python has a garbage collector that handles the deletion of the instances that are no longer referenced by any other instance or program. If we need to add logic inside a destructor method, we can implement it by using a special __del__ method. It is automatically called when all references of an instance are deleted. Here is the syntax of how to define a destructor method in Python:

def __del__(self):

print("Object is deleted.")

Share:

0 comments:

Post a Comment