Types of constructors in Python with examples

There are two types of constructors in Python. The first is the default constructor and the second parameterized constructor. Both are methods used to initialize the instance members of the class.

The Python __init__() method is called the constructor and is always invoked when a class object is created. 

class ClassName:
  def __init__(self):

Examples of different types of constructors in Python

Simple example code.

Default constructor:

It is a simple constructor without any argument to pass. Its definition has only one argument which is a reference to the instance being constructed.

class Test:

    def __init__(self):
        self.str1 = "Default"
        print("Test", self.str1)


obj = Test()

Output:

Types of constructors in Python

Parameterized Constructor:

If the constructor has parameters then it’s known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self.

class Person:

    def __init__(self, name, userid):
        self.name = name
        self.userid = userid


obj = Person('John', '[email protected]')
print(obj.userid)

Output: [email protected]

Do comment if you have any doubts and suggestions on this Python constructor tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.