understanding Encapsulation

amitmund June 05, 2026

Python Encapsulation - Complete Notes

What is Encapsulation?

Encapsulation is one of the four pillars of Object-Oriented Programming (OOP).

Encapsulation means:

Bundling data (variables) and methods (functions) together inside a class and controlling how that data is accessed or modified.

In simple words:

Encapsulation = Data + Methods + Access Control

The main goal is:

  • Protect data from accidental modification
  • Hide internal implementation details
  • Provide controlled access to data
  • Improve security and maintainability

Real-Life Example

Think of a Bank ATM.

When you withdraw money:

Insert Card
     ↓
Enter PIN
     ↓
Withdraw Money

You cannot directly access:

Bank Database
Account Records
Server Logic

The bank hides its internal implementation and only provides controlled methods.

This is Encapsulation.


Without Encapsulation

Consider a bank account:

class BankAccount:

    def __init__(self):
        self.balance = 1000

Create object:

account = BankAccount()

account.balance = -50000

print(account.balance)

Output:

-50000

Problem:

Anyone can directly modify balance.

This is dangerous.


Encapsulation Solution

Hide the balance:

class BankAccount:

    def __init__(self):
        self.__balance = 1000

Notice:

__balance

Two underscores indicate a private attribute.


Private Variables

class BankAccount:

    def __init__(self):
        self.__balance = 1000

Now:

account = BankAccount()

print(account.__balance)

Output:

AttributeError

Python prevents direct access.


Why Private Variables?

Suppose balance should never become negative.

Bad:

account.balance = -10000

Good:

account.withdraw(100)

The class decides whether the operation is valid.


Accessing Private Variables

Use methods.

Example:

class BankAccount:

    def __init__(self):
        self.__balance = 1000

    def get_balance(self):
        return self.__balance

Usage:

account = BankAccount()

print(account.get_balance())

Output:

1000

Modifying Private Variables

Provide controlled methods.

class BankAccount:

    def __init__(self):
        self.__balance = 1000

    def deposit(self, amount):
        self.__balance += amount

Usage:

account.deposit(500)

Output:

1500

Withdrawal Example

class BankAccount:

    def __init__(self):
        self.__balance = 1000

    def withdraw(self, amount):

        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient Balance")

Usage:

account.withdraw(200)

Output:

800

Now balance cannot be modified incorrectly.


Python Access Levels

Python does not have strict access modifiers like Java or C++.

Instead, Python uses naming conventions.


Public Variable

class Student:

    def __init__(self):
        self.name = "John"

Access:

student.name

Accessible everywhere.


Protected Variable

class Student:

    def __init__(self):
        self._name = "John"

Single underscore:

_name

Meaning:

Internal Use Only

Python still allows access.

print(student._name)

Works.

This is a convention, not enforcement.


Private Variable

class Student:

    def __init__(self):
        self.__name = "John"

Double underscore:

__name

Python performs name mangling.

Direct access:

student.__name

Produces:

AttributeError

Name Mangling

Many beginners think:

__balance

makes a variable truly private.

Actually Python changes:

__balance

into:

_BankAccount__balance

Internally.

Example:

class BankAccount:

    def __init__(self):
        self.__balance = 1000

Access:

account._BankAccount__balance

Output:

1000

Therefore:

Python does not create true private variables.
Python discourages direct access.

Why Use Double Underscore Then?

Because it:

  • Prevents accidental modification
  • Avoids name conflicts in inheritance
  • Signals that the variable is internal

It tells other programmers:

Don't touch this directly.

Getters and Setters

A common encapsulation technique.


Getter

Used to read data.

def get_balance(self):
    return self.__balance

Setter

Used to modify data.

def set_balance(self, amount):
    self.__balance = amount

Problem with Simple Setter

def set_balance(self, amount):
    self.__balance = amount

Now:

account.set_balance(-1000)

Still dangerous.


Better Setter

def set_balance(self, amount):

    if amount >= 0:
        self.__balance = amount
    else:
        print("Invalid Amount")

Now validation is enforced.


Encapsulation with Property Decorator

Python provides a cleaner approach.


Example

class BankAccount:

    def __init__(self):
        self.__balance = 1000

    @property
    def balance(self):
        return self.__balance

    @balance.setter
    def balance(self, amount):

        if amount >= 0:
            self.__balance = amount

Usage:

account = BankAccount()

print(account.balance)

account.balance = 5000

Looks like direct access but validation still occurs.


Why Encapsulation Matters

Without Encapsulation:

Anyone can change data.
No validation.
High risk of bugs.

With Encapsulation:

Data is protected.
Validation is possible.
Code becomes safer.
Implementation can change without affecting users.

Real-World Examples

Bank Account

Protect balance.

__balance

Employee

Protect salary.

__salary

Student

Protect marks.

__marks

E-Commerce

Protect inventory count.

__stock

Encapsulation and Security

Encapsulation does NOT make data completely secure.

Instead it:

Controls access
Encourages proper usage
Reduces accidental errors

Think of it as:

"Please use the official door."

instead of:

"You can never enter."

Interview Question

What is Encapsulation?

Encapsulation is the process of combining data and methods into a single unit (class) and restricting direct access to internal data by providing controlled access through methods.


Interview Question

Does Python Have Private Variables?

Not truly.

Python uses:

__variable

which triggers name mangling.

This discourages direct access but does not completely prevent it.


Rule to Remember

Public
    ↓
variable

Protected
    ↓
_variable

Private
    ↓
__variable

Final Takeaway

Encapsulation means:

Hide internal data
        +
Provide controlled access
        +
Protect object state

The most common tools are:

  • Public Variables
  • Protected Variables
  • Private Variables
  • Getter Methods
  • Setter Methods
  • @property
  • Validation Logic

Good encapsulation makes programs:

Safer
Cleaner
Easier to maintain
More reliable

Need a bit more details in Encapsulation vs class method

how really class method and encapsulation are different . Give some more example. Its like hiding internal data vs data using class variables.

Class Methods vs Encapsulation

One of the most common beginner confusions in Python OOP is:

What is the difference between Class Methods and Encapsulation?

At first glance they may look related because both can involve class data, but they solve completely different problems.


Short Answer

Encapsulation

Encapsulation answers:

Who is allowed to access or modify the data?

Focus:

Protecting Data

Class Method

Class Methods answer:

Which data should this method work with?

Focus:

Working With Class-Level Data

They Solve Different Problems

Think of a Bank.


Encapsulation Question

Can customers directly modify account balance?

Answer:

No

Customers should use:

deposit()
withdraw()

instead of modifying balance directly.

This is about:

Protection
Validation
Controlled Access

Class Method Question

How many bank accounts exist?

This information belongs to:

The Bank

not to any specific account.

This is about:

Class-Level Information

Example 1: Bank Account


Encapsulation Example

class BankAccount:

    def __init__(self):
        self.__balance = 0

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

Usage:

account = BankAccount()

account.deposit(500)

print(account.get_balance())

Goal

Hide Balance
Protect Balance
Control Access

User cannot safely do:

account.__balance = -10000

Encapsulation protects internal state.


Class Method Example

Suppose the bank wants to track:

Total Accounts Created

This belongs to the class.

class BankAccount:

    total_accounts = 0

    def __init__(self):
        BankAccount.total_accounts += 1

    @classmethod
    def get_total_accounts(cls):
        return cls.total_accounts

Usage:

a = BankAccount()
b = BankAccount()

print(BankAccount.get_total_accounts())

Output:

2

Goal

Work With Class Data

Nothing is hidden.

The method simply accesses:

total_accounts

which belongs to the class.


Visual Comparison

Encapsulation

BankAccount
      │
      ▼
 __balance
      │
      ▼
 Protected

Purpose:

Security
Validation
Controlled Access

Class Method

BankAccount
      │
      ▼
 total_accounts
      │
      ▼
 Shared By All Objects

Purpose:

Class-Level Operations

Example 2: Student School Name


Class Variable

class Student:

    school = "ABC School"

Every student shares:

ABC School

Class Method

class Student:

    school = "ABC School"

    @classmethod
    def get_school(cls):
        return cls.school

Usage:

Student.get_school()

Output:

ABC School

What Is Being Hidden?

Nothing

This is NOT encapsulation.

This is simply:

Accessing Class Data

Example 3: Encapsulation and Class Methods Together

Both concepts can exist in the same class.

class Employee:

    company = "Google"

    def __init__(self, salary):
        self.__salary = salary

    def get_salary(self):
        return self.__salary

    @classmethod
    def get_company(cls):
        return cls.company

Class Data

company

belongs to:

The Class

and is accessed through:

get_company()

which is a Class Method.


Encapsulated Data

__salary

belongs to:

Each Object

and is protected.

This is Encapsulation.


Example 4: Employee System

class Employee:

    company = "Google"

    def __init__(self, salary):
        self.__salary = salary

Shared Data

company

Shared by:

Employee 1
Employee 2
Employee 3

All employees belong to:

Google

Protected Data

__salary

Different for each employee.

Example:

Employee 1 → 50000
Employee 2 → 70000
Employee 3 → 100000

This information should be protected.

Therefore:

Encapsulation

Can Class Variables Be Encapsulated?

Yes.

class Employee:

    __company = "Google"

    @classmethod
    def get_company(cls):
        return cls.__company

Usage:

Employee.get_company()

Output:

Google

Direct access:

Employee.__company

Produces:

AttributeError

What Is Happening Here?

__company

provides:

Encapsulation

and

get_company()

is:

Class Method

Both concepts are working together.


The Real Difference

Encapsulation

Concerned With:

Access Control

Questions:

Should this data be hidden?
Who can modify it?
Should validation happen?

Tools:

__
getters
setters
@property

Class Method

Concerned With:

Class Data

Questions:

Does this method work with the class itself?
Does it use class variables?

Tool:

@classmethod

Easy Rule

When you see:

@classmethod

Think:

This method works with the CLASS.

When you see:

__balance

Think:

This data is PROTECTED.

Visual Summary

Encapsulation
      ↓
Protect Data

Class Method
      ↓
Work With Class Data

Interview Answer

Difference Between Encapsulation and Class Methods

Encapsulation is an OOP principle used to protect and control access to data using private variables, getters, setters, and properties.

Class Methods are methods that operate on class-level data and receive the class (cls) as their first parameter.

Encapsulation focuses on:

Protection and Access Control

Class Methods focus on:

Class-Level Operations

They are independent concepts and can be used separately or together.

0 Likes
4 Views

Filters

No filters available for this view.

Reset All