Python Encapsulation Foundation
public / private OOP 05 Foundation

Bundle data and methods; control access

Encapsulation binds data and methods together and restricts direct access using public and private access levels.

Picture this: private locker + public door

Keep _balance inside. deposit/withdraw are the only doors.

outside codecannot poke internals
→
deposit()public door
→
_balanceprotected data

What is encapsulation?

Encapsulation wraps data (attributes) and methods (functions) into a single unit called a class, and controls how the outside world accesses them using access modifiers.

UML Encapsulation Diagram

classDiagram
    class BankAccount {
      +deposit(amt)
      +withdraw(amt)
      -__balance: int
    }
    BankAccount : +deposit(amt)
    BankAccount : +withdraw(amt)
    BankAccount : -__balance
            
Public methods are exposed; private data is hidden inside the class.

Encapsulation Visual

Public Private
Only the public interface is accessible from outside; private data is protected.

Real-world analogy

A car's engine is encapsulated in metal—you can't access it directly. You control it through the steering wheel, pedals, and buttons (public interface). Private parts prevent damage.

Public (exposed)

  • Accessible from outside
  • No underscore prefix
  • Methods users call

Private (protected)

  • Internal use only
  • Underscore prefix: _method
  • Double underscore: __method

Encapsulation example

1class BankAccount:
2def __init__(self):
3self.__balance = 0 # Private
4def deposit(self, amt): # Public
5self.__balance += amt

Public vs Private

Press "Run one step" to see encapsulation

Good encapsulation

1account = BankAccount()
2account.deposit(100) # ✓ Allowed
3account.__balance = "hacked" # ✗ Not recommended