The __init__ method in Python is a special method that is automatically executed when an object of a class is created.
It is commonly called a constructor because it is used to initialize the object’s data.
What is a Constructor ?
A constructor is a special method that
- runs automatically when an object is created
- initializes object attributes
- sets the initial state of the object
In Python , the constructor method is named as __init__ .
Syntax :
Python
class ClassName: def __init__(self): statements - __init__ is a predefined method name
- self refers to the current object
- Python calls it automatically during object creation
Initializing Instance Variables :
Python
class Student: def __init__(self, name, age): self.name = name self.age = age def display(self): print(self.name, self.age) s1 = Student("Rahul", 22) s1.display() #output Rahul 22 Parameterized Constructor :
Python
class Employee: def __init__(self, emp_id, salary): self.emp_id = emp_id self.salary = salary Default Constructor :
Python
class Demo: def __init__(self): self.msg = "Hello" d = Demo() print(d.msg)