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.
def __init__(self):
# body of the constructor
There are two types of constructors in Dart:
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.
The following code shows how to use a default constructor in Python.
class Shot:# Creating default constructordef __init__(self):print("This is a default constructor")self.title = "Constructor in Python"# a method to display the data memberdef display_message(self):print(self.title)# creating object of the classs1_obj = Shot()# calling the instance method using the objects1_obj.display_message()
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.
The following code shows how to use a parameterized constructor in Python.
class Triangle:base = 0height = 0area = 0# parameterized constructordef __init__(self, b, h):self.base = bself.height = hdef areaOfTriangle(self):self.area = self.base * self.height * 0.5print("Area of triangle: " + str(self.area))# creating object of the class# this will invoke parameterized constructorobj = Triangle(5, 14)# perform calculationobj.areaOfTriangle()