PYTHON ENCAPSULATION (OOP)

Protect internal data integrity, control attribute access, and implement information hiding using public, protected, and private members in Python.

🔒 What is Encapsulation in Python?

Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It describes the bundling of data (attributes) and methods that operate on that data into a single unit (class), while restricting direct outside access to internal states.

Unlike strict languages like Java or C++, Python uses naming conventions to signal access levels: Public (normal variables), Protected (single leading underscore _), and Private (double leading underscore __).

1. Public, Protected, and Private Access Modifiers
Demonstrate how Python defines access levels using variable naming conventions.
Python
class Employee:
    def __init__(self, name, salary, pin):
        self.name = name          # Public attribute
        self._department = "IT"   # Protected attribute (warning convention)
        self.__pin = pin          # Private attribute (name mangled)

emp = Employee("Rahul Sharma", 55000, 4321)

print("Public Name:", emp.name)
print("Protected Department:", emp._department)

try:
    print(emp.__pin)  # Will raise AttributeError
except AttributeError as e:
    print("AttributeError caught:", e)
Output: Public Name: Rahul Sharma Protected Department: IT AttributeError caught: 'Employee' object has no attribute '__pin'
Real-Time Example 1: Bank Account Balance Protection
Secure sensitive financial balances inside a private attribute so unauthorized scripts cannot tamper with them directly.
Python
class BankAccount:
    def __init__(self, holder, initial_balance):
        self.holder = holder
        self.__balance = initial_balance  # Private balance

    def get_balance(self):
        return self.__balance

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

acc = BankAccount("Priya Singh", 25000)
acc.deposit(5000)
print("Current Balance:", acc.get_balance())
Output: Deposited ₹5000. New Balance: ₹30000 Current Balance: 30000
Real-Time Example 2: Getter and Setter Methods for Data Validation
Control data modification 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("Validation Error: Temperature out of bounds (-50°C to 100°C).")
        else:
            self.__celsius = value
            print(f"Temperature successfully updated to {self.__celsius}°C")

sensor = TemperatureSensor()
sensor.set_temperature(38)
sensor.set_temperature(150)  # Rejected by validation setter
print("Final Recorded Temperature:", sensor.get_temperature(), "°C")
Output: Temperature successfully updated to 38°C Validation Error: Temperature out of bounds (-50°C to 100°C). Final Recorded Temperature: 38 °C
Real-Time Example 3: Pythonic Property Decorators (@property)
Use @property and @setter decorators to manage private variables with clean property syntax.
Python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.__price = price

    @property
    def price(self):
        return self.__price

    @price.setter
    def price(self, new_price):
        if new_price < 0:
            print("Error: Price cannot be negative.")
        else:
            self.__price = new_price

prod = Product("Wireless Mouse", 450)
prod.price = 500   # Calls @price.setter
print("Updated Price:", prod.price)

prod.price = -100  # Trigger validation error
print("Price remains:", prod.price)
Output: Updated Price: 500 Error: Price cannot be negative. Price remains: 500
Real-Time Example 4: ATM PIN Security Manager
Encapsulate ATM PIN verification logic and prevent direct PIN reading or printing.
Python
class ATMCard:
    def __init__(self, cardholder, pin):
        self.cardholder = cardholder
        self.__pin = pin  # Strictly private PIN

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

    def update_pin(self, old_pin, new_pin):
        if self.authenticate(old_pin):
            self.__pin = new_pin
            return "PIN updated successfully."
        return "Authentication failed. Incorrect old PIN."

card = ATMCard("Amit Kumar", "1234")
print("Auth test (correct):", card.authenticate("1234"))
print("Update status:", card.update_pin("1234", "9999"))
Output: Auth test (correct): True Update status: PIN updated successfully.
Real-Time Example 5: Name Mangling Demonstration
Understand how Python internally rewrites private attributes as _ClassName__attribute (Name Mangling).
Python
class SecretVault:
    def __init__(self, secret_code):
        self.__secret = secret_code

vault = SecretVault("TOP_SECRET_99")

# Accessing via name mangled form (demonstration of python internals)
print("Accessed via Name Mangling:", vault._SecretVault__secret)
Output: Accessed via Name Mangling: TOP_SECRET_99
Real-Time Example 6: Read-Only Attributes
Create read-only attributes by providing a getter property without a corresponding setter method.
Python
class DatabaseRecord:
    def __init__(self, record_id):
        self.__record_id = record_id  # Immutable ID

    @property
    def record_id(self):
        return self.__record_id  # Getter only, no setter

rec = DatabaseRecord(1092)
print("Record ID:", rec.record_id)

try:
    rec.record_id = 9999
except AttributeError as e:
    print("AttributeError caught:", e)
Output: Record ID: 1092 AttributeError caught: can't set attribute 'record_id'
Real-Time Example 7: API Token Security Manager
Encapsulate API secret keys and restrict exposure in external logs.
Python
class APIConfig:
    def __init__(self, api_key):
        self.__api_key = api_key

    def get_masked_key(self):
        return f"****-****-{self.__api_key[-4:]}"

cfg = APIConfig("SECRET_KEY_AZ9912")
print("Masked Key for Display:", cfg.get_masked_key())
Output: Masked Key for Display: ****-****-9912
Real-Time Example 8: Employee Salary Encapsulation
Protect employee salary figures from arbitrary external modification while allowing controlled raises.
Python
class EmployeeRecord:
    def __init__(self, name, base_salary):
        self.name = name
        self.__salary = base_salary

    def give_raise(self, percentage):
        if percentage > 0:
            self.__salary += self.__salary * (percentage / 100)
            print(f"Raise applied! New salary: ₹{round(self.__salary, 2)}")

    def get_salary(self):
        return self.__salary

emp = EmployeeRecord("Sneha Patil", 50000)
emp.give_raise(10)
print("Final Salary:", emp.get_salary())
Output: Raise applied! New salary: ₹55000.0 Final Salary: 55000.0
Real-Time Example 9: Game Character Health Encapsulation
Encapsulate player health points so damage and healing methods manage boundaries correctly (0 to 100 HP).
Python
class Player:
    def __init__(self, name):
        self.name = name
        self.__hp = 100

    def take_damage(self, damage):
        self.__hp = max(0, self.__hp - damage)
        print(f"{self.name} took {damage} damage. HP: {self.__hp}/100")

    def heal(self, amount):
        self.__hp = min(100, self.__hp + amount)
        print(f"{self.name} healed {amount} HP. HP: {self.__hp}/100")

hero = Player("Arthur")
hero.take_damage(35)
hero.heal(20)
Output: Arthur took 35 damage. HP: 65/100 Arthur healed 20 HP. HP: 85/100