PYTHON CLASSES & OBJECTS (OOP)

Structure modular object-oriented applications using classes, constructors, methods, and instance variables in Python.

🏛️ What are Classes and Objects in Python?

Python is a multi-paradigm programming language that fully supports Object-Oriented Programming (OOP). A Class acts as a blueprint or template for creating objects, defining their attributes (variables) and behaviors (methods). An Object is an instance of a class that holds specific data values and can execute the methods defined in the class blueprint.

1. Basic Class Definition & Object Instantiation
Define a simple class using the class keyword and instantiate object instances from it.
Python
class Car:
    # Class attribute
    wheels = 4

# Instantiate objects
car1 = Car()
car2 = Car()

print("Car 1 wheels:", car1.wheels)
print("Car 2 wheels:", car2.wheels)
Output: Car 1 wheels: 4 Car 2 wheels: 4
Real-Time Example 1: The Constructor (__init__ method)
Use the __init__ constructor method to initialize unique instance attributes when an object is created.
Python
class Employee:
    def __init__(self, name, emp_id, salary):
        self.name = name          # Instance attribute
        self.emp_id = emp_id      # Instance attribute
        self.salary = salary      # Instance attribute

# Creating employee objects with distinct values
emp1 = Employee("Rahul Sharma", 101, 55000)
emp2 = Employee("Priya Singh", 102, 68000)

print(f"{emp1.name} (ID: {emp1.emp_id}) earns ₹{emp1.salary}")
print(f"{emp2.name} (ID: {emp2.emp_id}) earns ₹{emp2.salary}")
Output: Rahul Sharma (ID: 101) earns ₹55000 Priya Singh (ID: 102) earns ₹68000
Real-Time Example 2: Adding Instance Methods
Define methods inside classes that operate on object instance attributes using the self parameter.
Python
class BankAccount:
    def __init__(self, account_holder, balance):
        self.holder = account_holder
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited ₹{amount}. New Balance: ₹{self.balance}")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Withdrawal failed: Insufficient funds.")
        else:
            self.balance -= amount
            print(f"Withdrew ₹{amount}. Remaining Balance: ₹{self.balance}")

acc = BankAccount("Nikita Infotech", 25000)
acc.deposit(5000)
acc.withdraw(10000)
Output: Deposited ₹5000. New Balance: ₹30000 Withdrew ₹10000. Remaining Balance: ₹20000
Real-Time Example 3: The __str__ String Representation Method
Use the __str__ magic method to define a clean, readable string output when printing an object.
Python
class Product:
    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock

    def __str__(self):
        return f"Product: {self.name} | Price: ₹{self.price} | Stock: {self.stock} units"

prod = Product("Mechanical Keyboard", 1200, 15)
print(prod)  # Automatically calls __str__
Output: Product: Mechanical Keyboard | Price: ₹1200 | Stock: 15 units
Real-Time Example 4: Inheritance (Parent and Child Classes)
Reuse code by creating a child class that inherits attributes and methods from a parent class.
Python
# Parent Class
class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def login(self):
        return f"User '{self.username}' logged into system."

# Child Class inheriting from User
class Admin(User):
    def __init__(self, username, email, admin_level):
        super().__init__(username, email)  # Call parent constructor
        self.admin_level = admin_level

    def manage_users(self):
        return f"Admin {self.username} (Level {self.admin_level}) managing user accounts."

admin_user = Admin("admin_nikita", "admin@infotech.com", 5)
print(admin_user.login())
print(admin_user.manage_users())
Output: User 'admin_nikita' logged into system. Admin admin_nikita (Level 5) managing user accounts.
Real-Time Example 5: Method Overriding (Polymorphism)
Child classes can override parent methods to provide specialized behavior.
Python
class Notification:
    def send(self, message):
        return f"Sending generic notification: {message}"

class EmailNotification(Notification):
    def send(self, message):  # Overriding parent method
        return f"Sending EMAIL notification: {message}"

class SMSNotification(Notification):
    def send(self, message):    # Overriding parent method
        return f"Sending SMS notification: {message}"

notifs = [EmailNotification(), SMSNotification()]
for n in notifs:
    print(n.send("Your OTP is 4829."))
Output: Sending EMAIL notification: Your OTP is 4829. Sending SMS notification: Your OTP is 4829.
Real-Time Example 6: Encapsulation & Private Attributes
Protect sensitive data inside objects by making attributes private using double underscores (__).
Python
class SecureVault:
    def __init__(self, pin):
        self.__pin = pin  # Private attribute

    def verify_pin(self, entered_pin):
        return self.__pin == entered_pin

vault = SecureVault("4321")
print("Pin verification check:", vault.verify_pin("4321"))

# Trying to access vault.__pin directly would raise an AttributeError!
Output: Pin verification check: True
Real-Time Example 7: Getters and Setters
Control access to private attributes safely using getter and setter methods with validation checks.
Python
class TemperatureSensor:
    def __init__(self):
        self.__celsius = 25  # Private attribute

    def get_temperature(self):
        return self.__celsius

    def set_temperature(self, value):
        if value < -50 or value > 100:
            print("Error: Temperature out of valid range (-50°C to 100°C).")
        else:
            self.__celsius = value
            print(f"Temperature updated to {self.__celsius}°C")

sensor = TemperatureSensor()
sensor.set_temperature(38)
sensor.set_temperature(150)  # Invalid update
print("Current Temp:", sensor.get_temperature(), "°C")
Output: Temperature updated to 38°C Error: Temperature out of valid range (-50°C to 100°C). Current Temp: 38 °C
Real-Time Example 8: Class Methods vs Instance Methods
Use the @classmethod decorator and cls parameter to operate on class-level attributes shared across all instances.
Python
class Company:
    total_employees = 0  # Class attribute

    def __init__(self, name):
        self.name = name
        Company.total_employees += 1

    @classmethod
    def get_headcount(cls):
        return f"Total company headcount: {cls.total_employees} employees."

emp1 = Company("Rahul")
emp2 = Company("Priya")
emp3 = Company("Amit")

print(Company.get_headcount())
Output: Total company headcount: 3 employees.
Real-Time Example 9: Static Methods (@staticmethod)
Use @staticmethod for utility functions that belong inside a class namespace but do not access instance or class data.
Python
class MathUtility:
    @staticmethod
    def is_even(number):
        return number % 2 == 0

print("Is 24 even?", MathUtility.is_even(24))
print("Is 17 even?", MathUtility.is_even(17))
Output: Is 24 even? True Is 17 even? False