Categories
Computer Science

Object Oriented Programming – Encapsulation

Encapsulation is an Object-Oriented Programming (OOP) concept where data (attributes) and methods (functions) are bundled together in a class and access to the data is controlled to protect it from unintended interference or misuse.

  • Data hiding (restricting direct access to variables)
  • Better maintainability
  • Controlled access through getter and setter methods

Python does not have strict access modifiers like some other languages, but it uses naming conventions:

ModifierSyntax ExampleMeaning
Publicself.nameAccessible from anywhere
Protectedself._nameConvention: should not be accessed outside the class (still possible)
Privateself.__nameName mangling makes it harder to access from outside
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder # Public attribute
self._account_type = "Savings" # Protected attribute
self.__balance = balance # Private attribute
# Getter for balance
def get_balance(self):
return self.__balance
# Setter for balance with validation
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited ₹{amount}. New balance: ₹{self.__balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew ₹{amount}. Remaining balance: ₹{self.__balance}")
else:
print("Invalid withdrawal amount.")
# Usage
account = BankAccount("Rahul", 5000)
# Public access
print(account.account_holder) # ✅ Works
# Protected access (possible but discouraged)
print(account._account_type) # ⚠️ Works but not recommended
# Private access (will cause error)
# print(account.__balance) # ❌ AttributeError
# Correct way to access private data
print("Balance:", account.get_balance())
# Modify balance safely
account.deposit(2000)
account.withdraw(1000)
  1. Public: Accessible anywhere.
  2. Protected: Accessible but should be treated as internal.
  3. Private: Not directly accessible; use getters/setters.
  4. Name Mangling: Private attributes are internally renamed to _ClassName__attribute to avoid accidental access.

Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a comment