Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

Encapsulation

Encapsulation 20 minEncapsulation keeps related state and operations together and provides controlled ways to maintain their rules.

Encapsulation keeps related state and operations together and provides controlled ways to maintain their rules.

Validate changes before applying them and test that an object’s rules stay true across whole sequences of operations.

A class groups state and methods, but a public balance can still be assigned any value. Encapsulation means choosing the supported operations and keeping their rules in one place. Using the account from the previous lesson, we will follow an accepted withdrawal, a refused one, and a less obvious bypass: returning a mutable internal object.

Left: a bare balance number sitting in the open with an arrow straight through it to -9999, labelled "no guard — anyone can walk in". Right: the same balance behind a door with a guard checking "amount > balance?" before letting a withdrawal through, labelled "one door — the guard always runs"

A balance with a hole

The account from the last lesson has a serious gap: nothing stops this.

python

If this account's rule is “balance stays non-negative,” direct assignment bypasses it. We need a supported operation that checks a requested change, and callers that use it. In Python, this interface reduces accidental misuse; it does not prevent code from inspecting or altering internal attributes. The door in the illustration represents the supported operation, not an enforced privacy boundary.

Preparing this topic’s interactive investigation…

Guard before you act

First, route withdrawals through a method. Its contract for the non-negative amounts used here is: either deduct the entire amount and return True, or return False with the balance unchanged. The guard must run before mutation.

python

Get the order backwards and you build exactly the state you were trying to prevent:

broken — fix it

This should refuse the withdrawal and leave the balance at 100. It prints -400. Run it, then fix the order.

Test the rule across a sequence, not just one call

The balance rule is an invariant: something each supported operation should preserve when it was true beforehand. For a starting balance of 100:

Request Check against current balance Result Balance afterwards
withdraw 30 30 > 100 is false True 70
withdraw 500 500 > 70 is true False 70
withdraw 70 70 > 70 is false True 0

Equality must be allowed; changing > to >= would wrongly refuse the exact remaining balance. Returning False is also not enough on its own: the caller needs to trust that a refusal left the state unchanged.

The current method assumes non-negative amounts. withdraw(-10) passes its guard and adds ten, because subtracting a negative increases the balance. For an API accepting external requests, decide the input contract before implementing it: for example, integer minor units, positive withdrawal amounts, and a clear error for invalid input. Add that validation before any mutation. The exercises below isolate overdraft handling with ordinary non-negative amounts; they do not certify a complete payment system.

For a transfer exercise, write a reservation object with available = 3 and reserve(n). Choose whether zero is a valid no-op. Check requests 2, 2, 1, and -1, recording both the result and remaining capacity. A test of the final capacity alone can miss an incorrect success signal.

Validate at the door

Validation during setup prevents the ordinary constructor call from returning an account with an invalid opening balance. The instance already exists while __init__ runs; check before storing state or publishing a reference to self:

python

If setup raises, a = Account("Ada", -5) does not finish assigning the new instance to a. This is stronger than constructing, passing the object elsewhere, and validating later. It is not proof that an invalid object can never exist: later unchecked writes, or setup that exposes self before failing, can still break the design. See the object construction contract.

The underscore convention, and a read-only view

A leading underscore means internal implementation detail by convention. @property is separate: the line immediately above the method makes reading a.balance call that method automatically, without (). A getter with no setter lets this public name be read but not assigned. You do not need to know how to write decorators yet to use this built-in one:

python

With no setter, assigning to a property is refused outright — Python raises rather than quietly creating a second attribute that shadows the real one:

What happens when you run this?
class Account:
    def __init__(self, balance=0):
        self._balance = balance

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

a = Account(50)
a.balance = 999

Nothing stops a determined caller reaching for _balance directly — that's deliberate. Python trusts you and makes the intent obvious rather than enforcing it with the type system.

A read-only property can still expose mutable state

The earlier property returns a number. What changes if it returns a list?

python

No assignment to ledger.entries occurred. Reading the property returned the actual internal list; append then changed that list. “No setter” protects the attribute assignment path, not every operation on the returned object.

For this list of numbers, returning tuple(self._entries) gives a snapshot whose outer structure cannot be changed. Returning list(self._entries) gives an editable outer copy whose appends do not affect the ledger. Neither choice recursively copies mutable entries. The shared-reference example explains why. Choose the return contract deliberately: live view, shallow copy, or immutable snapshot are different promises.

Try changing the getter to return a tuple, then add a supported record(amount) method and call it instead of appending to the view. After recording another amount, should an earlier snapshot change? Explain your answer using which object each name refers to. Python's property documentation describes the access hooks; the contents returned by those hooks remain your design.

Quick practice

Step through a refusal and watch the balance simply not move:

step through it
1class Account:
2 def __init__(self, balance):
3 self.balance = balance
4 
5 def withdraw(self, amount):
6 if amount > self.balance:
7 return False
8 self.balance -= amount
9 return True
10 
11a = Account(100)
12ok1 = a.withdraw(30)
13ok2 = a.withdraw(500)
14print(a.balance, ok1, ok2)
What does this print?
class Wallet:
    def __init__(self):
        self._cash = 0

    def add(self, amount):
        self._cash += amount

w = Wallet()
w.add(10)
print(w._cash)
broken — fix it

Selling more than the stock holds should be refused, leaving count unchanged. Add the missing guard.


🎯 Your turn

Give Account a withdraw(self, amount) that refuses to overdraw — take nothing and return False when there aren't enough funds, otherwise deduct and return True. Then write safe_withdraw(start, amounts) which tries each withdrawal in turn and returns the final balance:

  • safe_withdraw(100, [30, 200, 20]) → 50 (the 200 is refused)
  • safe_withdraw(50, [50]) → 0 (exact is allowed)

Hint — guard first, deduct second. amount > self.balance is the test.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a thermostat to a full statement with refusals counted.

Your task
Give Account a withdraw(self, amount) that refuses to overdraw — it takes nothing out and returns False when there are insufficient funds, otherwise deducts and returns True. Then write safe_withdraw(start, amounts) which tries each withdrawal in turn and returns the final balance. Example: safe_withdraw(100, [30, 200, 20]) → 50, because the 200 is refused.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upRefuse a bad value

Define Thermostat starting at 20 with set_to(degrees) that ignores anything outside 5–30. Write final_temp(values) applying each and returning the temperature.

encapsulationguard
DrillThe underscore convention

Define Wallet storing its money in self._balance (leading underscore = internal), with add(amount) and a peek() returning it. Write wallet_after(amounts) adding each and returning the total.

encapsulationnaming
BuildA computed property

Define Circle taking radius, with area as a property (@property) returning 3.14159 * radius ** 2. Write circle_area(r) returning c.area — note: no parentheses.

encapsulationproperty
BossReject it at the door

Define Account whose __init__ raises ValueError if the opening balance is negative. Write open_account(amount) returning the balance, or -1 if opening was refused (catch the error).

encapsulationraiseguard
CapstoneThe account that can't go negative

Define Account(owner, balance) with deposit(amount) and withdraw(amount) returning True/False. Write statement(owner, start, moves) where each move is ["deposit", 50] or ["withdraw", 30], returning {"balance": ..., "refused": n} — the closing balance and how many moves were refused.

encapsulationguardloopdict
Project context and further resources
You're building a piece ofA bank account that can't go wrong
This piece — Account.withdraw(): Makes overdrawing impossible rather than merely discouraged.
Scenario A customer with £100 tries to take out £200. The account must decline rather than quietly going negative.
safe_withdraw.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
safe_withdraw(start, amounts) → floatApply each withdrawal that the account allows; return the balance.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.