Encapsulation

Encapsulation means bundling an object's data and the methods that operate on that data together inside a class — and then controlling access to that data. Without it, any code anywhere can corrupt your object's state.

The Problem with Public Data

If balance is public, nothing stops this:

account = BankAccount("Alice", 1000)
account.balance = -99999   # sets an impossible value
account.balance = "hello"  # sets wrong type entirely

Both lines are valid Python. The language will not stop you. Only encapsulation — controlling access through methods — can prevent this.

Encapsulation Fixes This

The first step is to hide balance behind an internal attribute like _balance and expose a safe method such as get_balance(). The next two lessons build on this with Python naming conventions and validation.

class BankAccount:
    def __init__(self, owner, balance):
        self._balance = balance  # _ signals: do not touch directly

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

    def get_balance(self):
        return self._balance

Why Encapsulation Matters at Scale

  • Large teams — other developers cannot accidentally corrupt your object
  • Maintenance — you can change internal implementation without breaking external code
  • Validation — setters can enforce business rules (no negative balances)
  • IB exam point: encapsulation is one of the four pillars of OOP

Your Task

  1. Rename self.balance to self._balance
  2. Update deposit() so it changes self._balance
  3. Add get_balance() to return the current balance
  4. Add one short comment explaining why direct access to balance is bad design. Use at least one of these words: problem, danger, invalid, or corrupt

After your refactor, account.deposit(500) followed by account.get_balance() should return 1500.

Section 1/4The Problem with Public Data

The Problem with Public Data

If balance is public, nothing stops this:

Encapsulation

Encapsulation means bundling an object's data and the methods that operate on that data together inside a class — and then controlling access to that data. Without it, any code anywhere can corrupt your object's state.

The Problem with Public Data

If balance is public, nothing stops this:

account = BankAccount("Alice", 1000)
account.balance = -99999   # sets an impossible value
account.balance = "hello"  # sets wrong type entirely

Both lines are valid Python. The language will not stop you. Only encapsulation — controlling access through methods — can prevent this.

Output:

Click "Check" to run your code.