Video courses for company/skill based Preparation
Purchase mock tests for company/skill building
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.
- 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.
def __init__( self , variables...):
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.
- The __del__ method is similar to destructor in c++ and Java.
- Destructors are used to destroying the object’s state.
def __del__( self ,):
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.