The __init__ method in Python is a special (built-in) method known as the constructor.
It is automatically called when a new object of a class is created and is used to initialize the object’s attributes.


FeatureDescription
PurposeInitializes an object’s attributes at the time of creation.
Syntaxdef __init__(self, parameters):
Called AutomaticallyYes, when a new instance of a class is created.
Special MethodOne of Python’s “dunder” (double underscore) methods.
Return TypeDoes not return anything (returns None by default).

🧩 Example 1: Basic Use of __init__

class Person:
    def __init__(self, name, age):
        self.name = name    # instance variable
        self.age = age      # instance variable

    def show(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

# Creating object
p1 = Person("Dheeraj", 24)
p1.show()

Output:

My name is Dheeraj and I am 24 years old.

🧩 Example 2: Default Values in __init__

class Car:
    def __init__(self, brand="Tesla", color="Black"):
        self.brand = brand
        self.color = color

car1 = Car()
car2 = Car("BMW", "Blue")

print(car1.brand, car1.color)
print(car2.brand, car2.color)

Output:

Tesla Black
BMW Blue

🧩 Example 3: Using __init__ for Computation During Initialization

class Rectangle:
    def __init__(self, length, width):
        self.area = length * width  # Calculated at initialization

rect = Rectangle(5, 3)
print("Area of rectangle:", rect.area)

Output:

Area of rectangle: 15

In Summary:

  • __init__ is the constructor method that initializes instance variables.
  • It is called automatically when an object is created.
  • It helps in setting up the initial state of an object.
  • It’s one of the most commonly used dunder (double underscore) methods in Python classes.

Scroll to Top