🏗️ What are Classes and Objects in Python?
A class is a blueprint used to define the data and behavior of an object. An object is an actual instance created from that blueprint. Classes allow related data and functions to be grouped together, making large applications easier to organize, reuse, and maintain.
Class
A blueprint that defines attributes and methods.
Object
A real instance created from a class.
Attribute
Data stored inside an object, such as name, price, or balance.
Method
A function defined inside a class that performs an operation.
Basic OOP Flow:
Create Class → Define Attributes & Methods → Create Object → Pass Object Data → Call Methods → Application Performs Operations
Create Class → Define Attributes & Methods → Create Object → Pass Object Data → Call Methods → Application Performs Operations
1. Creating a Simple Class and Object
A class can represent a real-world entity. Here, the
Student class contains a student's name and course.
Objects are created from the class.
Python
class Student:
def display_info(self):
print("Student information")
student1 = Student()
student1.display_info()
Output:
Student information
Real-Time Example 1: Student Management System
Educational applications can represent each student as an object.
The class stores student information and provides methods for
displaying that information.
Python
class Student:
def __init__(self, name, roll_number, course):
self.name = name
self.roll_number = roll_number
self.course = course
def display_student(self):
print("Name:", self.name)
print("Roll Number:", self.roll_number)
print("Course:", self.course)
student1 = Student(
"Rahul",
101,
"Python Programming"
)
student1.display_student()
Output:
Name: Rahul
Roll Number: 101
Course: Python Programming
Real-Time Example 2: Bank Account
Banking software can use objects to represent customer accounts.
The account object can store the account holder and balance while
methods perform deposits and withdrawals.
Python
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
print("Deposited: ₹", amount)
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print("Withdrawn: ₹", amount)
else:
print("Insufficient balance")
def show_balance(self):
print("Account Holder:", self.holder)
print("Current Balance: ₹", self.balance)
account = BankAccount("Priya", 10000)
account.deposit(3000)
account.withdraw(2500)
account.show_balance()
Output:
Deposited: ₹ 3000
Withdrawn: ₹ 2500
Account Holder: Priya
Current Balance: ₹ 10500
Real-Time Example 3: Employee Management
A company's HR application can represent each employee as an object.
Employee objects can store department, salary, and other information
while methods perform employee-related operations.
Python
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def give_bonus(self, amount):
self.salary += amount
def display(self):
print("Employee:", self.name)
print("Department:", self.department)
print("Salary: ₹", self.salary)
employee = Employee(
"Amit",
"IT",
60000
)
employee.give_bonus(10000)
employee.display()
Output:
Employee: Amit
Department: IT
Salary: ₹ 70000
Real-Time Example 4: E-Commerce Product
Online shopping systems can model products using classes.
Each product object contains information such as name, price,
and stock quantity.
Python
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def purchase(self, quantity):
if quantity <= self.stock:
self.stock -= quantity
total = self.price * quantity
print("Product:", self.name)
print("Quantity:", quantity)
print("Total: ₹", total)
else:
print("Not enough stock")
product = Product(
"Wireless Mouse",
1200,
10
)
product.purchase(2)
print("Remaining Stock:", product.stock)
Output:
Product: Wireless Mouse
Quantity: 2
Total: ₹ 2400
Remaining Stock: 8
Real-Time Example 5: Constructor __init__()
The
__init__() method runs automatically when an object
is created. It is commonly used to initialize the object's attributes.
Python
class Customer:
def __init__(self, name, email):
self.name = name
self.email = email
customer = Customer(
"Sneha",
"sneha@example.com"
)
print("Customer Name:", customer.name)
print("Customer Email:", customer.email)
Output:
Customer Name: Sneha
Customer Email: sneha@example.com
Real-Time Example 6: Multiple Objects from One Class
One class can be used to create many independent objects.
This is one of the major advantages of object-oriented programming.
Python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(
self.brand,
self.model
)
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "City")
car3 = Car("Hyundai", "Creta")
car1.display()
car2.display()
car3.display()
Output:
Toyota Camry
Honda City
Hyundai Creta
Real-Time Example 7: Encapsulation
Encapsulation means keeping data and the operations that work on
that data together inside a class. A private-style attribute using
__ can prevent direct access from outside the class.
Python
class SecureAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = SecureAccount(5000)
account.deposit(2000)
print("Account Balance: ₹", account.get_balance())
Output:
Account Balance: ₹ 7000
Real-Time Example 8: Inheritance
Inheritance allows a child class to reuse attributes and methods
from a parent class. This is useful when different types of objects
share common behavior.
Python
class Vehicle:
def start(self):
print("Vehicle started")
class Car(Vehicle):
def drive(self):
print("Car is driving")
car = Car()
car.start()
car.drive()
Output:
Vehicle started
Car is driving
Real-Time Example 9: Method Overriding
A child class can provide its own implementation of a method
inherited from the parent class. This allows different object types
to perform the same operation differently.
Python
class Payment:
def process(self):
print("Processing payment")
class CreditCardPayment(Payment):
def process(self):
print("Processing credit card payment")
class UPIPayment(Payment):
def process(self):
print("Processing UPI payment")
payment1 = CreditCardPayment()
payment2 = UPIPayment()
payment1.process()
payment2.process()
Output:
Processing credit card payment
Processing UPI payment
Real-Time Example 10: Polymorphism
Polymorphism allows different object types to respond to the same
method call in their own way. This is especially useful in systems
that support multiple implementations of the same operation.
Python
class EmailNotification:
def send(self):
print("Sending notification by Email")
class SMSNotification:
def send(self):
print("Sending notification by SMS")
class PushNotification:
def send(self):
print("Sending Push notification")
notifications = [
EmailNotification(),
SMSNotification(),
PushNotification()
]
for notification in notifications:
notification.send()
Output:
Sending notification by Email
Sending notification by SMS
Sending Push notification
Real-Time Example 11: Class Variable vs Instance Variable
An instance variable belongs to a specific object, while a class
variable is shared by instances of the class. This can be useful
for tracking shared information such as the number of employees
created.
Python
class Employee:
company = "Tech Solutions"
employee_count = 0
def __init__(self, name):
self.name = name
Employee.employee_count += 1
employee1 = Employee("Rahul")
employee2 = Employee("Priya")
employee3 = Employee("Amit")
print("Company:", Employee.company)
print("Total Employees:", Employee.employee_count)
Output:
Company: Tech Solutions
Total Employees: 3
Real-Time Example 12: Class Method
A
@classmethod receives the class itself as its first
argument. It is useful when a method needs to work with class-level
information or provide an alternative way to create objects.
Python
class Employee:
company = "Tech Solutions"
def __init__(self, name):
self.name = name
@classmethod
def company_name(cls):
return cls.company
employee = Employee("Ravi")
print("Employee:", employee.name)
print("Company:", Employee.company_name())
Output:
Employee: Ravi
Company: Tech Solutions
Real-Time Example 13: Static Method
A
@staticmethod does not require access to either
instance data or class data. It is useful for utility operations
that logically belong to a class.
Python
class Order:
@staticmethod
def calculate_gst(amount):
return amount * 0.18
amount = 5000
gst = Order.calculate_gst(amount)
print("Order Amount: ₹", amount)
print("GST: ₹", gst)
print("Total: ₹", amount + gst)
Output:
Order Amount: ₹ 5000
GST: ₹ 900.0
Total: ₹ 5900.0
Real-Time Example 14: Complete E-Commerce Order System
Here is a larger real-world example combining classes, objects,
constructors, methods, encapsulation, and object state to model
a simple shopping order.
Python
class Order:
def __init__(self, customer, product, price, quantity):
self.customer = customer
self.product = product
self.price = price
self.quantity = quantity
self.status = "Pending"
def calculate_total(self):
return self.price * self.quantity
def confirm_order(self):
self.status = "Confirmed"
def display_order(self):
print("Customer:", self.customer)
print("Product:", self.product)
print("Quantity:", self.quantity)
print("Total: ₹", self.calculate_total())
print("Status:", self.status)
order = Order(
"Neha",
"Laptop",
65000,
1
)
order.confirm_order()
order.display_order()
Output:
Customer: Neha
Product: Laptop
Quantity: 1
Total: ₹ 65000
Status: Confirmed
Real-Time Example 15: Object Composition
Composition means one object contains or uses another object.
This is common in real applications where larger objects are built
from smaller objects.
Python
class Address:
def __init__(self, city, pincode):
self.city = city
self.pincode = pincode
class Customer:
def __init__(self, name, address):
self.name = name
self.address = address
def display(self):
print("Customer:", self.name)
print("City:", self.address.city)
print("Pincode:", self.address.pincode)
address = Address(
"Pune",
"411001"
)
customer = Customer(
"Arjun",
address
)
customer.display()
Output:
Customer: Arjun
City: Pune
Pincode: 411001
Summary of Python Classes & Objects
- Class: A blueprint used to create objects and define their attributes and methods.
- Object: An instance of a class containing its own data and state.
- __init__(): The constructor method commonly used to initialize object attributes.
- self: Refers to the current object instance and is used to access its attributes and methods.
- Encapsulation: Keeps related data and behavior together and can restrict direct access to implementation details.
- Inheritance: Allows a class to reuse or extend behavior from another class.
- Polymorphism: Allows different objects to respond to the same method call according to their own implementation.
- Class Method: A method that receives the class as its first argument and is commonly used for class-level operations.
- Static Method: A utility method that does not depend on instance or class state.
- Composition: Allows larger objects to be built using other objects.
- Real-World Modeling: Classes and objects are useful for representing customers, employees, products, orders, accounts, vehicles, students, payments, and many other entities.