🏗️ What is a Constructor in Python?
A constructor is a special method used to initialize an object when it is created. In Python, the commonly used constructor method is __init__(). It allows us to assign initial values to object attributes and prepare the object for use.
__init__()
The method commonly used to initialize an object when it is created.
self
Refers to the current object and is used to access its attributes.
Parameters
Values passed during object creation to initialize object data.
Object State
The data stored inside an object after initialization.
Constructor Flow:
Create Class → Define
Create Class → Define
__init__()
→ Create Object
→ Pass Initial Data
→ __init__() Runs Automatically
→ Object Is Ready to Use
1. Basic Constructor Example
The
__init__() method initializes the attributes of an
object. It runs automatically when the object is created.
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Rahul", 25)
print("Name:", person1.name)
print("Age:", person1.age)
Output:
Name: Rahul
Age: 25
2. How __init__() Works
When an object is created, Python automatically calls the
__init__() method after the object has been created.
This method is commonly used to initialize the object's state.
Python
class Employee:
def __init__(self, name):
print("Constructor executed")
self.name = name
employee = Employee("Amit")
print("Employee:", employee.name)
Output:
Constructor executed
Employee: Amit
Important:
Creating
Employee("Amit") automatically causes
Python to call __init__() for that object.
Real-Time Example 1: Student Registration
A college management system can use a constructor to initialize
student information when a new student record is created.
Python
class Student:
def __init__(self, student_id, name, course, year):
self.student_id = student_id
self.name = name
self.course = course
self.year = year
def display_student(self):
print("Student ID:", self.student_id)
print("Name:", self.name)
print("Course:", self.course)
print("Year:", self.year)
student = Student(
101,
"Priya",
"Computer Science",
2
)
student.display_student()
Output:
Student ID: 101
Name: Priya
Course: Computer Science
Year: 2
Real-Time Example 2: Bank Account
A banking application can use a constructor to initialize account
information such as account number, customer name, and opening balance.
Python
class BankAccount:
def __init__(self, account_number, customer_name, balance):
self.account_number = account_number
self.customer_name = customer_name
self.balance = balance
def show_account(self):
print("Account:", self.account_number)
print("Customer:", self.customer_name)
print("Balance: ₹", self.balance)
account = BankAccount(
"ACC1001",
"Ravi",
25000
)
account.show_account()
Output:
Account: ACC1001
Customer: Ravi
Balance: ₹ 25000
Real-Time Example 3: Constructor with Default Values
Constructor parameters can have default values. This is useful when
an application has optional information that may not always be supplied.
Python
class Product:
def __init__(self, name, price=0):
self.name = name
self.price = price
product1 = Product("Keyboard", 1200)
product2 = Product("Mouse")
print(product1.name, product1.price)
print(product2.name, product2.price)
Output:
Keyboard 1200
Mouse 0
Real-Time Example 4: Multiple Objects Using One Constructor
A single class constructor can initialize many independent objects.
Each object receives its own values.
Python
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
employee1 = Employee("Anita", "HR", 45000)
employee2 = Employee("Vikram", "IT", 65000)
employee3 = Employee("Sneha", "Finance", 55000)
print(employee1.name, employee1.department)
print(employee2.name, employee2.department)
print(employee3.name, employee3.department)
Output:
Anita HR
Vikram IT
Sneha Finance
Real-Time Example 5: Constructor + Instance Methods
The constructor initializes the object's data while instance methods
perform operations using that initialized data.
Python
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
def display_details(self):
print("Brand:", self.brand)
print("Model:", self.model)
print("Price: ₹", self.price)
car = Car(
"Toyota",
"Fortuner",
4000000
)
car.display_details()
Output:
Brand: Toyota
Model: Fortuner
Price: ₹ 4000000
Real-Time Example 6: E-Commerce Product Initialization
E-commerce applications can create product objects with a constructor
that initializes product ID, name, price, and stock quantity.
Python
class Product:
def __init__(self, product_id, name, price, stock):
self.product_id = product_id
self.name = name
self.price = price
self.stock = stock
def show_product(self):
print("Product ID:", self.product_id)
print("Product:", self.name)
print("Price: ₹", self.price)
print("Stock:", self.stock)
product = Product(
501,
"Laptop",
65000,
20
)
product.show_product()
Output:
Product ID: 501
Product: Laptop
Price: ₹ 65000
Stock: 20
Real-Time Example 7: Constructor Validation
A constructor can validate input values before assigning them to
object attributes. This helps prevent invalid initial object state.
Python
class Employee:
def __init__(self, name, salary):
self.name = name
if salary >= 0:
self.salary = salary
else:
self.salary = 0
employee = Employee(
"Arjun",
-5000
)
print("Name:", employee.name)
print("Salary:", employee.salary)
Output:
Name: Arjun
Salary: 0
Real-world use:
Constructor validation can prevent an object from starting with
invalid or unexpected data.
Real-Time Example 8: Constructor with Calculated Values
A constructor can calculate derived information during initialization.
For example, a shopping cart item can automatically calculate its total.
Python
class CartItem:
def __init__(self, product, price, quantity):
self.product = product
self.price = price
self.quantity = quantity
self.total = price * quantity
item = CartItem(
"Headphones",
2000,
3
)
print("Product:", item.product)
print("Quantity:", item.quantity)
print("Total: ₹", item.total)
Output:
Product: Headphones
Quantity: 3
Total: ₹ 6000
Real-Time Example 9: Constructor with Lists
A constructor can initialize collections such as lists. Initializing
the list inside
__init__() gives each object its own list.
Python
class Order:
def __init__(self, order_id, customer):
self.order_id = order_id
self.customer = customer
self.items = []
order = Order(
1001,
"Kiran"
)
order.items.append("Laptop")
order.items.append("Mouse")
order.items.append("Keyboard")
print("Order ID:", order.order_id)
print("Customer:", order.customer)
print("Items:", order.items)
Output:
Order ID: 1001
Customer: Kiran
Items: ['Laptop', 'Mouse', 'Keyboard']
Important:
Creating
self.items = [] inside the constructor ensures
that each Order object gets its own separate list.
Real-Time Example 10: Constructor and Inheritance
When a child class inherits from a parent class, it can use
super().__init__() to execute the parent constructor
and initialize inherited attributes.
Python
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self, name, department):
super().__init__(name)
self.department = department
employee = Employee(
"Meena",
"IT"
)
print("Name:", employee.name)
print("Department:", employee.department)
Output:
Name: Meena
Department: IT
Real-Time Example 11: Constructor vs Normal Method
A constructor is used for object initialization, while a normal
method is normally called explicitly to perform an operation.
| Constructor | Normal Method |
|---|---|
Commonly written as __init__()
|
Can have any valid method name |
| Called automatically during object initialization | Normally called explicitly |
| Used to initialize object state | Used to perform operations |
| Runs when an object is created | Runs when the application calls the method |
Python
class User:
def __init__(self, name):
self.name = name
print("Constructor called")
def login(self):
print(self.name, "logged in")
user = User("Rahul")
user.login()
Output:
Constructor called
Rahul logged in
Real-Time Example 12: Hospital Patient Registration
A hospital management application can use a constructor to initialize
patient information whenever a new patient record is created.
Python
class Patient:
def __init__(self, patient_id, name, age, department):
self.patient_id = patient_id
self.name = name
self.age = age
self.department = department
def display(self):
print("Patient ID:", self.patient_id)
print("Name:", self.name)
print("Age:", self.age)
print("Department:", self.department)
patient = Patient(
1001,
"Suresh",
45,
"Cardiology"
)
patient.display()
Output:
Patient ID: 1001
Name: Suresh
Age: 45
Department: Cardiology
Real-Time Example 13: Complete Employee Payroll System
A payroll application can use a constructor to initialize employee
information and calculate derived information such as annual salary.
Python
class Employee:
def __init__(
self,
employee_id,
name,
department,
monthly_salary
):
self.employee_id = employee_id
self.name = name
self.department = department
self.monthly_salary = monthly_salary
self.annual_salary = monthly_salary * 12
def display(self):
print("Employee ID:", self.employee_id)
print("Name:", self.name)
print("Department:", self.department)
print("Monthly Salary: ₹", self.monthly_salary)
print("Annual Salary: ₹", self.annual_salary)
employee = Employee(
101,
"Neha",
"Software Development",
75000
)
employee.display()
Output:
Employee ID: 101
Name: Neha
Department: Software Development
Monthly Salary: ₹ 75000
Annual Salary: ₹ 900000
Important Constructor Rules
Keep these rules in mind when working with constructors in Python.
-
The commonly used constructor method is
__init__(). - It is called automatically when an object is initialized.
-
selfrefers to the current object instance. - Constructor parameters can initialize object attributes.
- Constructor parameters can have default values.
- Constructors can perform input validation.
- Constructors can calculate derived object values.
-
super().__init__()can be used to call a parent class constructor. -
Mutable instance attributes such as lists should normally be
initialized inside
__init__().
Remember:
The constructor prepares an object for use. When an application
creates an object that needs initial data,
__init__()
is commonly used to establish that object's initial state.
Summary of Python Constructors
- Constructor: A method used to initialize an object's state when the object is created.
- __init__(): The commonly used Python method for initializing object attributes.
- self: Refers to the current object instance and is used to access instance attributes and methods.
- Initialization: Assigns the initial values required by an object.
- Default Values: Constructor parameters can provide default values when arguments are not supplied.
- Validation: Constructors can check incoming data before storing it.
- Calculated Attributes: Constructors can calculate values derived from the supplied data.
- super().__init__(): Allows a child class to call the parent class constructor.
- Object State: After initialization, the object's attributes represent its starting state.
- Real-World Applications: Constructors are useful for initializing students, employees, customers, bank accounts, products, orders, patients, and many other application objects.