Default constructor in Python with example

The Python default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.

def __init__(self):
    # body of the constructor

A constructor is a method with always has a name init and the name init is prefixed and suffixed with a double underscore(__). It’s declared a constructor using def keyword, just like methods.

Example Default constructor in Python

The constructors are to initialize/ assign value to the data members of the class when an object of the class is created.

class Test:

    # default constructor
    def __init__(self):
        self.msg = "Default constructor"

    # a method for printing data members
    def display(self):
        print(self.msg)


# creating object
obj = Test()
obj.display()

Output:

Default constructor in Python

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.