Python Constructor (__init__ Method)

What is a Constructor?

A constructor is a special method in a class that is automatically called when a new object is created. In Python, the constructor method is named __init__.

Why Use a Constructor?

  • To initialize object properties when the object is created.
  • To avoid setting attributes manually after object creation.

Syntax of a Constructor

class ClassName:
   def __init__(self, arguments):
       self.attribute = arguments

Example 1: Simple Constructor

class Student:
   def __init__(self, name, age):
       self.name = name
       self.age = age
s1 = Student("Ravi", 21)
print(s1.name)
print(s1.age)

Output:

Ravi
21

Explanation:

  • __init__() is called automatically when s1 is created.
  • self.name is assigned "Ravi" and self.age is assigned 21.
  • print(s1.name) → prints "Ravi".
  • print(s1.age) → prints 21

Example 2: Constructor with Default Values

class Car:
   def __init__(self, brand="Honda", model="City"):
       self.brand = brand
       self.model = model
c1 = Car()
c2 = Car("Toyota", "Fortuner")
print(c1.brand, c1.model)  # Honda City
print(c2.brand, c2.model)  # Toyota Fortuner

Output:

Honda City
Toyota Fortuner

Explanation:

  • c1 = Car() uses default values, so:
    • c1.brand = "Honda", c1.model = "City"
  • c2 = Car("Toyota", "Fortuner") uses custom values.
  • Each print shows the object's attributes.

Example 3: Multiple Objects with Same Constructor

class Employee:
   def __init__(self, emp_id, emp_name):
       self.emp_id = emp_id
       self.emp_name = emp_name
e1 = Employee(101, "Alice")
e2 = Employee(102, "Bob")
print(e1.emp_name)
print(e2.emp_name)

Output:

Alice
Bob

Explanation:

  • e1 and e2 are different objects with unique data.
  • The constructor takes different arguments for each.
  • Each object retains its own data using self.

Summary

ExamplePurposeOutput Example
1Basic object creation with dataRavi21
2Use default and custom constructor argsHonda CityToyota Fortuner
3Multiple instances with same logicAliceBob