Python Constructors¶
A constructor is a special type of method which is used to initialize the instance members of the class.
The __init__() Function¶
In Python, the __init__() method is the constructor. It is automatically called when a new object of a class is created.
class Student:
# Constructor
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
print("Constructor called, object created!")
# Object creation
s1 = Student("Vishnu", 101)
Types of Constructors¶
1. Default Constructor¶
A simple constructor which doesnβt accept any arguments. Its 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 takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the user.
Destructors
Python also has a destructor method __del__() which is called when an object is about to be destroyed.