🏗️ What is a Constructor in Python?
A constructor is a special method in a class used to create and initialize an object's instance variables.
In Python, the constructor is defined using the magic method __init__(self, ...).
Whenever a new object instance is instantiated from a class, Python automatically invokes the __init__ method, allowing you to pass startup values and set up internal states.
1. Basic Parameterized Constructor (__init__)
Define a parameterized constructor that accepts arguments during object creation to set unique attribute values.
Python
class Student:
# Parameterized Constructor
def __init__(self, name, roll_number, course):
self.name = name
self.roll_number = roll_number
self.course = course
# Instantiating objects with constructor arguments
s1 = Student("Rahul Sharma", 101, "Computer Science")
s2 = Student("Priya Singh", 102, "Data Science")
print(f"{s1.name} (Roll: {s1.roll_number}) is enrolled in {s1.course}")
print(f"{s2.name} (Roll: {s2.roll_number}) is enrolled in {s2.course}")
Output:
Rahul Sharma (Roll: 101) is enrolled in Computer Science
Priya Singh (Roll: 102) is enrolled in Data Science
Real-Time Example 1: Constructor with Default Parameter Values
Provide default fallback values inside the constructor parameters for optional object attributes.
Python
class UserAccount:
def __init__(self, username, email, role="Subscriber", active=True):
self.username = username
self.email = email
self.role = role
self.active = active
# Using default values
u1 = UserAccount("rahul123", "rahul@gmail.com")
# Overriding default values
u2 = UserAccount("nikita_dev", "nikita@infotech.com", role="Administrator")
print(f"User 1: {u1.username} | Role: {u1.role}")
print(f"User 2: {u2.username} | Role: {u2.role}")
Output:
User 1: rahul123 | Role: Subscriber
User 2: nikita_dev | Role: Administrator
Real-Time Example 2: Database Connection Initializer
Use constructors to establish connection parameters when initializing database manager objects.
Python
class DatabaseConnection:
def __init__(self, host, port, database_name):
self.host = host
self.port = port
self.database_name = database_name
self.connected = True
print(f"Connecting to database '{self.database_name}' at {self.host}:{self.port}...")
db = DatabaseConnection("localhost", 3306, "nikita_db")
print("Connection Status:", "Active" if db.connected else "Offline")
Output:
Connecting to database 'nikita_db' at localhost:3306...
Connection Status: Active
Real-Time Example 3: E-Commerce Shopping Cart Constructor
Initialize an empty list inside the constructor to track items added to a customer shopping cart.
Python
class ShoppingCart:
def __init__(self, customer_name):
self.customer_name = customer_name
self.items = [] # Empty initial list
def add_item(self, product_name, price):
self.items.append({"name": product_name, "price": price})
print(f"Added '{product_name}' to {self.customer_name}'s cart.")
cart = ShoppingCart("Rahul Sharma")
cart.add_item("Wireless Mouse", 450)
cart.add_item("Mechanical Keyboard", 1200)
print("Total Cart Items:", len(cart.items))
Output:
Added 'Wireless Mouse' to Rahul Sharma's cart.
Added 'Mechanical Keyboard' to Rahul Sharma's cart.
Total Cart Items: 2
Real-Time Example 4: Constructor Validation Rules
Enforce validation rules inside the constructor to reject invalid data upon object creation.
Python
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative.")
self.balance = initial_balance
try:
acc = BankAccount("Priya Singh", -500)
except ValueError as e:
print("Validation Error Caught:", e)
Output:
Validation Error Caught: Initial balance cannot be negative.
Real-Time Example 5: Inheritance and super() in Constructors
Use
super().__init__() in a child class constructor to inherit and reuse parent attributes.
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, emp_id, salary):
super().__init__(name, age) # Initialize parent attributes
self.emp_id = emp_id
self.salary = salary
emp = Employee("Rahul Sharma", 28, 101, 65000)
print(f"Employee: {emp.name}, Age: {emp.age}, ID: {emp.emp_id}, Salary: ₹{emp.salary}")
Output:
Employee: Rahul Sharma, Age: 28, ID: 101, Salary: ₹65000
Real-Time Example 6: Default Constructor (Implicit / Zero-Arg)
If no
__init__ method is defined, Python provides a default implicit constructor.
Python
class DefaultConfig:
theme = "dark"
version = "1.0.0"
cfg = DefaultConfig()
print("Default Theme:", cfg.theme)
print("Default Version:", cfg.version)
Output:
Default Theme: dark
Default Version: 1.0.0
Real-Time Example 7: Multiple Object Instances with Unique States
Demonstrate how the constructor ensures each object instance maintains its own independent state.
Python
class LightBulb:
def __init__(self, room_name):
self.room_name = room_name
self.is_on = False
def toggle(self):
self.is_on = not self.is_on
bulb_kitchen = LightBulb("Kitchen")
bulb_living = LightBulb("Living Room")
bulb_kitchen.toggle() # Turn kitchen light on
print(f"{bulb_kitchen.room_name} light ON?", bulb_kitchen.is_on)
print(f"{bulb_living.room_name} light ON?", bulb_living.is_on)
Output:
Kitchen light ON? True
Living Room light ON? False
Real-Time Example 8: Game Character Constructor
Initialize game character stats (health, level, weapons) upon instantiation.
Python
class GameCharacter:
def __init__(self, name, character_class):
self.name = name
self.character_class = character_class
self.health = 100
self.level = 1
def get_status(self):
return f"{self.name} [{self.character_class}] - HP: {self.health} | Level: {self.level}"
hero = GameCharacter("Aragorn", "Warrior")
print(hero.get_status())
Output:
Aragorn [Warrior] - HP: 100 | Level: 1
Real-Time Example 9: API Configuration Constructor
Configure API endpoint URLs, request timeouts, and authorization headers using a constructor.
Python
class APIClient:
def __init__(self, base_url, api_key, timeout_sec=30):
self.base_url = base_url
self.api_key = api_key
self.timeout_sec = timeout_sec
client = APIClient("https://api.nikitainfotech.com/v1", "secret_key_123")
print(f"API Base URL: {client.base_url} | Timeout: {client.timeout_sec}s")
Output:
API Base URL: https://api.nikitainfotech.com/v1 | Timeout: 30s