🏗 Constructor

Last Updated: 05 Sept 2025


A constructor is a special method in Python classes which is used to initialize objects with values at the time of object creation.

  • In Python, the constructor is always named __init__().
  • The __init__ method is called automatically when an object is created from a class.

✏️ Basic Syntax

class ClassName:
    def __init__(self, param1, param2):
         # initialization code
  • self is a reference to the current instance of the class (Object).You can use any name instead of self.
  • param1 and param2 are the parameters of the constructor.

Example 1

class Person:
    def __init__(self, name, age):
        self.name = name # attributes//instance variables
        self.age = age

p1 = Person("Amit", 20)
p2 = Person("Sadhu", 1)

print(p1.name, p1.age)  # Amit 20
print(p2.name, p2.age)  # Sadhu 1

variable are the attributes of the class.It can be following types:

  • Instance Variables: Belong to object (instance). They are unique to each object and defined using self.
  • Class Variables (Static Variables): A Variables that are shared by all instances of the class. it can be Access by using class name or object name.

Example 2

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

c1 = Car("Toyota", "Corolla")
c2 = Car("Tesla", "Model 3")

print(c1.brand, c1.model)  # Toyota Corolla
print(c2.brand, c2.model)  # Tesla Model 3

💡 Quick Practice