Python Encapsulation

Introduction Reading Time: 10 min

Table of Contents

Description

Encapsulation is an object-oriented programming principle that binds data (variables) and methods (functions) together within a class, restricting direct access to some of the object’s components.
This is used to:
Protect object integrity by preventing unwanted access/modification.
Hide internal implementation (data hiding).
Control how attributes are accessed and modified using access modifiers.
Python doesn't have true access modifiers like other languages (Java, C++), but it uses naming conventions to emulate:<>br Public
Protected (by convention)
Private (name mangling)

Prerequisites

  • Understanding of classes, objects, and methods
  • Basic variable declaration in Python
  • Knowledge of method definitions and self

Examples

Here's a simple program in Python:

✅ Public Members (Default in Python)
Accessible from anywhere.

class Student:
    def __init__(self, name):
        self.name = name  # public attribute

s = Student("Ravi")
print(s.name)  # Output: Ravi
✅ Protected Members (_)
Accessible within the class and subclasses by convention.

class Person:
    def __init__(self, name, age):
        self._age = age  # protected variable

class Employee(Person):
    def show_age(self):
        print("Age is:", self._age)

e = Employee("Raj", 30)
e.show_age()  # Output: Age is: 30
🔸 Note: Technically still accessible outside, but it’s discouraged.

✅ Private Members (__)
Name mangled to make it harder to access directly.
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private variable

    def get_balance(self):
        return self.__balance

acc = BankAccount(10000)
print(acc.get_balance())     # ✅ Output: 10000
# print(acc.__balance)      ❌ AttributeError
print(acc._BankAccount__balance)  # 🔓 Still accessible via name mangling (not recommended)
✅ Setter and Getter Methods
Used to control access to private data (encapsulation in action).
class User:
    def __init__(self):
        self.__password = None  # private variable

    def set_password(self, pwd):
        # You can add validations here
        self.__password = pwd

    def get_password(self):
        return self.__password

u = User()
u.set_password("secret123")
print(u.get_password())  # Output: secret123

      

Real-World Applications

Banking Systems: Restrict direct access to account balance

Authentication Systems: Hide passwords or tokens

Game Development: Protect game state variables (like health, lives)

Medical Software: Encapsulate patient records

Where topic Can Be Applied

Security and sensitive data protection

Clean software design and modularity

Implementation of APIs and SDKs

Enforcing business logic using getter/setter logic

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

What is encapsulation in Python?

What are access modifiers? Does Python support them?

How is private data implemented in Python?

What is the purpose of name mangling?

Explain the use of getter and setter methods.

Is it possible to access private members outside the class in Python?