What Is A Constructor In Python?

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeWhat is a constructor in Python?

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 classs1_obj = Shot() # calling the instance method using the objects1_obj.display_message()Run

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 constructorobj = Triangle(5, 14) # perform calculationobj.areaOfTriangle() Run

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » What Is A Constructor In Python