Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is a constructor in Python?

Maria Elijah

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.

Syntax

def __init__(self):
    # body of the 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 Shot:
 
    # Creating default constructor
    def __init__(self):
        print("This is a default constructor")
        self.title = "Constructor in Python"
 
    # a method to display the data member
    def display_message(self):
        print(self.title)
 
 
# creating object of the class
s1_obj = Shot()
 
# calling the instance method using the object
s1_obj.display_message()

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

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

class Triangle:
    base = 0
    height = 0
    area = 0
     
    # parameterized constructor
    def __init__(self, b, h):
        self.base = b
        self.height = h

 
    def areaOfTriangle(self):
        self.area = self.base * self.height * 0.5
        print("Area of triangle: " + str(self.area))
 
# creating object of the class
# this will invoke parameterized constructor
obj = Triangle(5, 14)
 
# perform calculation
obj.areaOfTriangle()
 

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring