What are Constructors and Destructors?
- Constructors and destructors are special methods in Object Oriented Programming (OOP) languages like Python.
- Constructors are used to initialize an object when it is created, while destructors are used to clean up memory when an object is no longer needed.
What is a Constructor in Python?
- A constructor in Python is a special method with the name
__init__
. - The
__init__
method is called automatically when an object is created, and it can be used to set initial values for object properties.
Syntax
The Syntax of a Constructor in Python is:
Python
class ClassName:
def __init__(self, arg1, arg2, ...):
# Initialization code
# ....
- The
self
parameter is used to refer to the current object being created. - The constructor can accept any number of arguments, and these arguments can be used to set the initial values for object properties.
Example
Python
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
s = Student("John Doe", 123)
print(s.name) # John Doe
print(s.roll) # 123
What is a Destructor in Python?
- A destructor in Python is a special method with the name
__del__
. - The
__del__
method is called automatically when an object is no longer needed, and it can be used to clean up any resources used by the object.
Syntax
The Syntax of a Destructor in Python is:
Python
class ClassName:
def __del__(self):
# Clean up code
- The
self
parameter is used to refer to the current object being destroyed.
Example
Python
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def __del__(self):
print("Deleting object")
s = Student("John Doe", 123)
del s # Deleting object
Note:
- In Python, the garbage collector automatically frees up memory used by objects that are no longer needed, so it is not necessary to explicitly define destructors in most cases.
- However, destructors can still be useful for releasing resources like file handles or network connections when an object is no longer needed.