Constructors in Python
In this article, I am going to discuss Constructors in Python with examples. Please read our previous article where we discussed Class and Objects in Python with examples. As part of this article, we are going to discuss the following pointers which are related to Constructors in Python.
- What are Constructors
- Is constructor mandatory in Python?
- Can a constructor be called explicitly?
- How many parameters can constructor have?
- Parameterised and Non-Parameterized Constructors in Python
- Difference between a method and constructor in Python
- Difference between a method and a function
Constructors in Python
In any programming language, constructor is a method which, by default, is invoked whenever an instance(object) for a class is created. It’s not required to explicitly invoke or call it.
Generally, the constructor is used for initial intializations that are required during the object creation. In python, constructor is a method with the name ‘__init__’. The methods first parameter should be ‘self’ (referring to the current object).
Is constructor mandatory in Python?
No, it’s not mandatory for a class to have a constructor. It completely is based on our requirement whether to have a constructor or not. At the time of object creation if any initialization is required then we should go for a constructor, else it’s not needed. Without a constructor also, the python program is valid.
Example: Constructor (demo3.py)
class Employee: def __init__ (self): print("constructor is executed automatically at the time of object creation") emp = Employee()
In this demo3.py, we just created an object and haven’t called any method. But, we have something printed to the console, which is done by the constructor “__init__”. Hence, we can conclude that it is automatically called at the time of object creation,
Can a constructor be called explicitly?
Yes, we can call constructor explicitly with object name. But since the constructor gets executed automatically at the time of object creation, it is not recommended to call it explicitly.
Example: Calling Constructor Explicitly (demo4.py)
class Employee: def __init__ (self): print("constructor") emp = Employee() emp.__init__()
Note: The constructor is not mandatory to be included. In case, if we haven’t included a constructor then python will, internally, include an empty constructor. We can check this by using dir(class_name) built in method.
Example: Empty Constructor in Python(demo5.py)
class Sample: def m1(self): print("m1 is instance method called with object name") s = Sample() s.m1() print(dir(Sample))
How many parameters can constructor have?
Constructor can have any number of parameters depending on the requirement. There is no limit for it. All the values which we need or want to be initialized during the object creation should be passed on to the constructor. A variable, by default, should be referring to the current instance should always be there in the constructor i.e self.
Example: Non Parameterized Constructor in Python(demo6.py)
class Employee: def __init__ (self): print("constructor") print(self) emp = Employee()
In demo.6.py, the constructor doesn’t have any parameters except self. The self contains the current object address.
Example: Non Parameterized Constructor in Python(demo7.py)
class Employee: def __init__(self): self.id = 1 print("Employee id is: ", self.id) e1 = Employee() e2 = Employee() e3 = Employee()
Parameterised Constructor in Python:
In demo7.py also, the constructor doesn’t have any parameters except self. In constructor we initialized a variable ‘id’ with value 1. All the objects created for the above class will have the same value for id. If we want different values for different instances then we need to go for a parameterised constructor.
Example: Parameterised Constructor in Python(demo8.py)
class Employee: def __init__(self, id): self.id = id print("Employee id is: ", self.id) e1 = Employee(1) e2 = Employee(2)
In demo8.py, we have used a parameterised constructor with id as a parameter. At the time of object creation, we need to pass a value so that it can be stored in the id variable for the object. While referring to the id of the object ‘e1’, self will be referring to e1. Hence, self.id gives 1 as the output. While referring to the id of the object ‘e2’, self will be referring to e2. Hence, self.id gives 2 as the output. This explains us what self exactly is and how it can be used.
Example: Parameterised Constructor in Python(demo9.py)
class Employee: def __init__(self, id,name): self.id=id self.name=name def display(self): print("Hello my id is :", self.id) print("My name is :", self.name) e1=Employee(1, 'Nithin') e1.display() e2=Employee(2, 'Arjun') e2.display()
Difference between a method and constructor:
Difference between a method and a function
Functions which are written inside a class can be accessed only with the objects created from the class. They are called methods. We can say that methods are nothing but functions which can be referenced by the objects of the class.
In the next article, I am going to discuss Types of Variables in a Class in Python. Here, in this article, I try to explain Constructors in Python. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.