HOME HTML EDITOR C JAVA PHP python

Python Encapsulation

Encapsulation is the practice of bundling an object's data (attributes) and methods together inside a class while restricting direct access to internal state. In Python, this is achieved through naming conventions (_protected and __private) and controlled getter/setter or @property methods.

1. Protected (_single) & Private (__double) Attributes

A leading underscore (_balance) signals internal/protected use by convention, while a double underscore (__pin) triggers name mangling so it is not directly accessed as obj.__pin:

class BankAccount:
    def __init__(self, owner, balance, pin):
        self.owner = owner        # Public
        self._balance = balance   # Protected convention
        self.__pin = pin          # Private (name-mangled)

    def get_pin(self):
        return self.__pin

acc = BankAccount("Riya", 15000, 4321)
print(acc.owner)
print(acc._balance)
print("PIN via method:", acc.get_pin())

2. Controlled Updates with Validation Methods

Instead of letting external code set invalid values directly, expose methods that validate data before updating state:

class Wallet:
    def __init__(self, balance=0):
        self.__balance = balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return f"Deposited Rs.{amount}"
        return "Invalid deposit amount"

    def get_balance(self):
        return self.__balance

w = Wallet(1000)
print(w.deposit(500))
print("Current Balance:", w.get_balance())

3. Using the @property Decorator

@property lets you access a method like an attribute while still validating changes in its setter:

class UserProfile:
    def __init__(self, age):
        self._age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("Age cannot be negative")
        self._age = value

user = UserProfile(24)
print("Age:", user.age)
user.age = 25
print("Updated Age:", user.age)
Tip: Python relies on conventions and clean interfaces rather than strict access modifiers — use @property when you want attribute-like syntax backed by validation logic.