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): #body
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.
class Hello: def __init__(self): print("Hey, Coder!") h1=Hello()
Output: 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
This type of constructor has multiple parameters along with self keyword.
class Hello: def __init__(self,name): self.name=name print("hey",self.name) h1= Hello("JOHN DOE")
Output : Hey, JOHN DOE
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") h1=Hello()
Output: Hey, coder
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 ", self.name) h1= Hello() h1.show()
Output : My name is John doe