__init__ Constructor in Python


What is __init__ in Python?

The __init__() method in Python is known as the constructor. It is a special method that gets called automatically when a new object of a class is created. It allows the class to initialize the object's attributes.

Syntax of __init__ Method:

class ClassName:
    def __init__(self, parameters):
        # initialization code
  • The first argument is always self, which refers to the current object
  • You can pass additional arguments to set instance variables

Example 1: Basic Usage of __init__

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

    def greet(self):
        print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

# Creating object
p1 = Person("Alice", 25)
p1.greet()

Output:

Hi, I'm Alice and I'm 25 years old.


Example 2: Default Values in __init__

class Car:
    def __init__(self, brand="Toyota", model="Corolla"):
        self.brand = brand
        self.model = model

    def show(self):
        print(f"Brand: {self.brand}, Model: {self.model}")

car1 = Car()
car2 = Car("Tesla", "Model 3")

car1.show()
car2.show()

Output:

Brand: Toyota, Model: Corolla
Brand: Tesla, Model: Model 3

Why Use __init__ in Python?

  • To initialize instance variables
  • To customize object creation
  • To enforce required arguments when an object is created

Difference Between __init__ and a Normal Method

Feature __init__() Normal Method
Called Automatically Yes, when object is created No, you call it manually
Purpose Initializes object state Defines object behavior
Return Value Always returns None (implicitly) Can return any value

Can We Have Multiple __init__ Methods?

Python does not support method overloading directly. But you can use default arguments or *args / **kwargs:

class Example:
    def __init__(self, a=None):
        if a:
            print("Initialized with:", a)
        else:
            print("Initialized with no argument")

ex1 = Example()
ex2 = Example("Python")

Output:

Initialized with no argument
Initialized with: Python

Encapsulation Using __init__

class User:
    def __init__(self, username, password):
        self.username = username
        self.__password = password  # private attribute

u = User("admin", "1234")
print(u.username)
# print(u.__password)  # This will raise AttributeError