In Python, a Constructor is a special type of method that is automatically called when an object of a class is instantiated. Its primary purpose is to initialize (assign values) to the data members of the class when an object is created.
In Python, the method name __init__ (short for initialization) is reserved for the constructor. It is one of Python’s "magic methods" or "dunder methods" (double underscore).
Automatic Execution: You do not call obj.__init__(). It runs the moment you write obj = ClassName().
The self Parameter: The first argument of a constructor is always self. It represents the specific instance of the object being created, allowing the constructor to differentiate between multiple objects of the same class.
Memory Allocation: While the class defines the structure, the constructor sets up the initial state in the memory allocated for that object.
Default Constructor: A simple constructor that doesn’t accept any arguments (except self). It usually initializes attributes with default values.
Parameterized Constructor: A constructor that accepts arguments, allowing you to pass specific data to the object at the time of creation.
This is the most common use case, where you pass data to customize each object.
class Student: # Parameterized Constructor def __init__(self, name, age, course): self.name = name # Instance variable self.age = age # Instance variable self.course = course # Instance variable print(f"Object created for {self.name}") def display_details(self): print(f"Name: {self.name}, Age: {self.age}, Course: {self.course}") # Passing arguments during object creation s1 = Student("Rahul", 20, "Python") s2 = Student("Priya", 22, "Data Science") s1.display_details()
If you don't define an __init__ method, Python provides an empty default constructor. However, you can define your own default constructor like this:
class SystemInfo: def __init__(self): self.status = "Active" self.version = 1.0 def show(self): print(f"System Status: {self.status}, Version: {self.version}") # No arguments needed sys = SystemInfo() sys.show()
| Benefit | Description |
| Consistency | Ensures every object starts with a valid state. |
| Code Efficiency | Consolidates setup logic in one place instead of setting attributes manually after creation. |
| Validation | You can add logic inside __init__ to check if the data being passed is valid before saving it. |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION