Constructor in python

A constructor is a method which is used for the purpose of initializing the variable or instance member of class.

Constructor in python is created by __init__() function with self keyword. The self keyword is used to access attributes and methods of classes.

Constructor is executed once we create the Object of class.

Constructor Syntax:

def __init__(self):
    # body of the constructor

How to create constructor in python?

In Python, the init() function is used for creating constructor. This method is named when the class is initialize. It accepts the self-keyword which allows you for accessing the attributes or method of the class .

Every class must have a constructor, means if we are not creating constructor in python class, then python will automatically create default constructor.

Consider the subsequent example to initialize the worker class attributes.

Example: Constructor implementation program

class Student:
    def __init__(self, name, id):
        self.name = name
        self.id = id
    def display(self):
        print("ID:Name:", (self.id, self.name))
stud1 = Student("John", 101)
stud2 = Student("David", 102)

stud1.display()  #accessing class method display
Constructor-in-Python-example

What are the types of constructor in python?

There are three types of constructor in python Parameterized, Non-parameterized and default constructor.

  1. Parameterized Constructor – A constructor with parameter is known as parameterized Constructor.
  2. Non-parameterized Constructor- A constructor without parameter is know as Non-parameterized Constructor.
  3. Default Constructor- The automatically created constructor in python is called as Default constructor.

Example: Default Constructor implementation

class DefaultConstructor:

	# default constructor
	def __init__(self):
		self.message = "Hello World"

	# a method for printing data members
	def print_message(self):
		print(self.message)


# creating object of the class
obj = DefaultConstructor()

# calling the instance method using the object obj
obj.print_message()

Default-constructor-Example

Was this article helpful?
YesNo

3 thoughts on “Constructor in python”

  1. Excellent way of explaining, and fastidious
    article
    to take information about my presentation subject matter, which i am going to
    present in institution of higher education.

    Reply
  2. Pingback: Social share tool

Leave a Comment