Constructor in Python

In this tutorial, we will learn about Constructor in Python.

In Object-oriented Programming, a special kind of method is used to instantiate an object.
It initializes values to the data members of the class whenever an object is created.
In other languages like C++, and Java the constructor has the same name as the method. However, in Python constructors in Python are independent of the class name and has their own name. The method __init__() is the constructor in Python and is called when an object is created.
The purpose of defining a constructor is, it provides state and uniqueness to the object.
In Python, a constructor is invoked automatically when we create an object.

Syntax of a constructor :

def __init__(self):

Creating a constructor :
We need to define a method called __init__() inside our class.
This method takes an argument known as self. In addition to it, we can define many parameters.

Example Code:

class Hello:
def __init__(self):
print("Hey, Coder!")

Hey, Coder!

In the example we can see that, constructor is called when the object is created.

Different types of constructor:
There are three types of constructors, they are
1)Parameterized Constructor
This type of constructor has multiple parameters along with self keyword.


class Hello:
    def __init__(self,name):

h1= Hello("JOHN DOE")
Output :


2)Non-parameterized constructor
This type of constructor does not have any other argument, it just has self as an argument.


class Hello:
    def __init__(self)
    print("Hey, coder")

Hey, coder

3)Default constructor
When we don’t include the constructor in the class, then it becomes default constructor. It does not do any tasks but initializes the objects .


class Hello:
    name="John doe"
    def show(self):
        print("My name is ",
h1= Hello()
Output : 

My name is John doe


Leave a Reply

Your email address will not be published. Required fields are marked *