Sitemap
Tanvi Jain

Tanvi Jain

Software Developer | MSCS Grad Student @SBU | Ex-Developer at TCS Digital | Ex-Intern at TCSion

What is a constructor in Python?

2 min readMar 15, 2024

--

Press enter or click to view image in full size

Constructors are a special type of method used to initialize an object. Constructors are responsible for assigning values to the data members of a class when an object is created.

Constructors in C++, Dart, or Java have the same name as the class, but Python considers constructors differently. In Python, a constructor is called by the __init__() method, and it is invoked whenever an object is created.

Get Tanvi Jain’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax:

def __init__(self):
# initializations

init is one of the reserved functions in Python. In Object Oriented Programming, it is known as a constructor.

Types of constructors

There are two types of constructors in Dart:

  1. Default constructor
  2. Parameterized constructor

Default constructor

The default constructor is a constructor that takes no arguments. It contains only one argument called self, which is a reference to the instance that is being built.

Code

The following code shows how to use a default constructor in Python.

class Details:
def __init__(self):
print("This is a default constructor")
obj1=Details()
#Output
#This is a default constructor

Parameterized constructor

Parameterized constructors are constructors that have parameters and a reference to the instance being created called self. The self reference serves as the first argument.

Code

class Details:
def __init__(self, name, age):
self.name = name
self.age = age
obj1 = Details("Tanvi", "24")
print(obj1.name, "is ", obj1.age, "years old.")
#Output
#Tanvi is 24 years old.

--

--

Tanvi Jain
Tanvi Jain

Software Developer | MSCS Grad Student @SBU | Ex-Developer at TCS Digital | Ex-Intern at TCSion