Skip to content

Default constructor in Python with example

  • by

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 keywords, just like methods.

Example Default constructor in Python

The constructors are to initialize/ assign values 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 or suggestions on this Python constructor tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading