Nearby lessons

100 of 159

Python - Constructor

📌 What You Will Learn
  • Understand what a constructor is and its purpose
  • Use the __init__() method to initialize instance variables
  • Know that a constructor executes only once per object
  • Explain why Python does not support traditional constructor overloading
  • Implement constructor overloading with default and variable length arguments

What Is a Constructor?

A constructor is a special method used to initialize an object.

In Python, the constructor method is named __init__.

Why Is It Used?

Constructors are mainly used to declare and initialize instance variables when an object is created.

For every object, the constructor is executed automatically and only once.

Constructor Example

🐍Code Cell
1class Student:
2 
3 def __init__(self, name, rollno, marks):
4 self.name = name
5 self.rollno = rollno
6 self.marks = marks
7 
8 def display(self):
9 print("Student Name:", self.name)
10 print("Rollno:", self.rollno)
11 print("Marks:", self.marks)
12 
13 
14s1 = Student("Durga", 101, 80)
15s1.display()
16 
17s2 = Student("Sunny", 102, 100)
18s2.display()
Output
Student Name: Durga
Rollno: 101
Marks: 80
Student Name: Sunny
Rollno: 102
Marks: 100

Explanation

The constructor __init__(self, name, rollno, marks) accepts three values.

When each object is created, the constructor executes automatically and stores the values inside that object using self.

Each call to Student(...) runs the constructor once, so the constructor executes twice for the two objects created above.

Constructor Executes Only Once Per Object

The following program shows that the constructor executes once for every object created, while a method executes only when it is explicitly called.

🐍Code Cell
1class Test:
2 
3 def __init__(self):
4 print("Constructor execution.")
5 
6 def m1(self):
7 print("Method execution.")
8 
9 
10t1 = Test()
11t2 = Test()
12t3 = Test()
13 
14t1.m1()
Output
Constructor execution.
Constructor execution.
Constructor execution.
Method execution.

Differences Between Methods and Constructors

Method Constructor
The name of a method can be any name. The constructor name should always be __init__.
A method executes only if we call it. A constructor executes automatically when an object is created.
A method can be called any number of times for the same object. A constructor is executed only once for each object.
A method is used to perform business logic or operations. A constructor is mainly used to declare and initialize instance variables.

Constructor Overloading

Constructor overloading means defining multiple constructors with different numbers of arguments.

However, Python does not support constructor overloading. If multiple constructors are declared, only the last constructor is available.

🐍Code Cell
1class Test:
2 
3 def __init__(self):
4 print("No-Arg Constructor")
5 
6 def __init__(self, a):
7 print("One-Arg Constructor")
8 
9 def __init__(self, a, b):
10 print("Two-Arg Constructor")
11 
12 
13# t1 = Test()
14# t1 = Test(10)
15 
16t1 = Test(10, 20)
Output
Two-Arg Constructor

Explanation

Only the Two-Arg Constructor remains available because the latest __init__() definition replaces all previous definitions.

Calling Test() or Test(10) would raise a TypeError because the available constructor requires two arguments.

Constructor with Default Arguments

Based on our requirement, we can declare a constructor with default arguments.

By giving default values to the parameters, the same constructor can be used with zero, one, two, or three arguments.

🐍Code Cell
1class Test:
2 
3 def __init__(self, a=None, b=None, c=None):
4 print("Constructor with 0|1|2|3 number of arguments")
5 
6 
7t1 = Test()
8t2 = Test(10)
9t3 = Test(10, 20)
10t4 = Test(10, 20, 30)
Output
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments

Constructor with Variable Number of Arguments

We can also declare a constructor with a variable number of arguments using the *a parameter.

When *a is used, all the values passed while creating the object are collected into a tuple, so the same constructor can accept any number of arguments.

🐍Code Cell
1class Test:
2 
3 def __init__(self, *a):
4 print("Constructor with variable number of arguments")
5 
6 
7t1 = Test()
8t2 = Test(10)
9t3 = Test(10, 20)
10t4 = Test(10, 20, 30)
11t5 = Test(10, 20, 30, 40, 50, 60)
Output
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments

Comparison of Constructor Types

Constructor Type Number of Arguments
Normal Constructor Fixed number of arguments
Constructor with Default Arguments 0, 1, 2, or 3 arguments (as defined)
Constructor with Variable Arguments Any number of arguments
📝 Key Takeaways
  • A constructor is a special method named __init__()
  • It runs automatically when an object is created and executes only once per object
  • Its main purpose is to declare and initialize instance variables
  • The constructor is optional; Python provides a default constructor if none is defined
  • Python keeps only the last constructor, so overloading is achieved with default or *args arguments

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8