Python Encapsulation

🐍 Python Encapsulation — Complete Guide

Encapsulation is an OOP principle that restricts direct access to some attributes and methods of a class.
It protects data and allows controlled access through getter and setter methods.


🔹 1️⃣ What is Encapsulation?

  • Bundling data (attributes) and methods inside a class.

  • Hiding sensitive data using private variables.

  • Providing controlled access to attributes.


🔹 2️⃣ Access Modifiers in Python

Modifier How it works Example
Public Can be accessed anywhere self.name
Protected (single underscore _) Should not be accessed outside class (convention) self._salary
Private (double underscore __) Cannot be accessed directly outside class self.__balance

🔹 3️⃣ Example: Private Variables

class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # public
self.__balance = balance # private

def show_balance(self):
print(f"Balance: {self.__balance}")

b = BankAccount("Vipul", 5000)
print(b.owner) # Vipul
b.show_balance() # Balance: 5000

# print(b.__balance) # ❌ Error: private variable

Private variables cannot be accessed directly from outside the class.


🔹 4️⃣ Accessing Private Variables (Name Mangling)

Python internally changes __balance to _ClassName__balance:

print(b._BankAccount__balance) # 5000

Direct access is possible but not recommended.


🔹 5️⃣ Getter and Setter Methods

Use methods to access or modify private variables safely.

class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance

# Getter
def get_balance(self):
return self.__balance

# Setter
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Balance cannot be negative!")

b = BankAccount("Vipul", 5000)
print(b.get_balance()) # 5000

b.set_balance(7000)
print(b.get_balance()) # 7000

b.set_balance(-100) # Balance cannot be negative!


🔹 6️⃣ Using @property Decorator

Python allows getter/setter using decorators:

class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary

@property
def salary(self):
return self.__salary

@salary.setter
def salary(self, value):
if value >= 0:
self.__salary = value
else:
print("Salary cannot be negative!")

e = Employee("Riya", 50000)
print(e.salary) # 50000

e.salary = 60000
print(e.salary) # 60000

e.salary = -100 # Salary cannot be negative!

@property makes your code cleaner and Pythonic.


🔹 7️⃣ Summary Table

Feature Description
Public Accessible everywhere (self.name)
Protected Single underscore _var (convention)
Private Double underscore __var (restricted access)
Getter Method to get private attribute
Setter Method to safely set private attribute
@property Pythonic way to create getter/setter

🔹 8️⃣ Benefits of Encapsulation

  • Data protection from accidental modification

  • Clean and maintainable code

  • Ability to add validation logic in setter methods

  • Hides internal implementation details

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *