Skip to content

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.

class GeekforGeeks:
    def __init__(self):
        self.geek = "GeekforGeeks"

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.

class Addition:
    def __init__(self, f, s):
        self.first = f
        self.second = s

Destructors

Python also has a destructor method __del__() which is called when an object is about to be destroyed.