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()
Do comment if you have any doubts and suggestions on this Python constructor tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.