A class defines related data and behaviours; objects are instances created from that class. Encapsulation groups the methods that manage an object’s state. Identify the constructor, attributes and the public operations in the example.
Watch out: Methods need a reference to the current instance, normally self. Avoid changing internal state without checking invariants.
Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.
class BankAccount:
def __init__(self, owner, balance=0):
if balance < 0: raise ValueError("negative opening balance")
self.owner = owner
self._balance = balance
@property
def balance(self): return self._balance
def deposit(self, amount):
if amount <= 0: raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance: raise ValueError("invalid withdrawal")
self._balance -= amount
account = BankAccount("Sam", 50)
account.deposit(25)
account.withdraw(10)
2 · Independent programming challenge
Create a BankAccount class with encapsulated balance and deposit/withdraw methods. Download the starter, design your solution, and add tests before revealing the answer.
Stretch task: investigate time/space complexity or data validation, then write an evaluation of your approach.
Show reference solution after attempting the task
class BankAccount:
def __init__(self, owner, balance=0):
if balance < 0: raise ValueError("negative opening balance")
self.owner = owner
self._balance = balance
@property
def balance(self): return self._balance
def deposit(self, amount):
if amount <= 0: raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance: raise ValueError("invalid withdrawal")
self._balance -= amount
account = BankAccount("Sam", 50)
account.deposit(25)
account.withdraw(10)
assert account.balance == 65
print(account.balance)
3 · Debug and explain
Change one boundary condition in the starter or reference program. Predict which test fails, then repair it and document why.
Concept check: Why hide a class balance behind methods?
Reveal explanation
It allows validation and protects the object’s invariants rather than allowing arbitrary changes.
4 · Assess your learning
Describe the algorithm or design in your own words; include a normal test, a boundary test and an invalid input. Compare your answers with the reference solution and record one improvement.
Separate an object’s state (attributes) from its behaviour (methods). When designing a class, decide which invariants should always be true and which methods are allowed to update the stored values.
Quick check: Why make an attribute private by convention?
Check: To signal that access should normally be controlled through the class interface, protecting its intended invariants.