21.1 Introduction to Encapsulation
On Part 1 every attribute was public — any code could read or change it directly. That is risky: nothing stops a careless line from setting a bank balance to a negative number. Real programs protect their data.
The fix is encapsulation: make the attributes private so outside code cannot touch them directly, then provide getter and setter methods as the only doorway in and out. The setter can check a value before storing it. By the end of this page you will hide data, read it with getters, update it with setters, and reject invalid values.
- Private attributes, encapsulation, getters and setters.
- The public-class basics are on Part 1 (OOP Classes); inheritance is on Part 4.
| Term | Meaning |
|---|---|
| Encapsulation | Keeping an object’s data and methods together in one class and hiding the data from outside code. Like a sealed capsule — you use it through buttons, not by reaching inside. |
| Private attribute | An attribute that can only be used inside its own class. In Python a __ prefix makes it private; in pseudocode the keyword is PRIVATE. |
| Public | A member that any code can access. In pseudocode PUBLIC; methods are usually public. |
| Getter | A method that returns the value of a private attribute, e.g. get_balance(). |
| Setter | A method that updates a private attribute, often after checking the new value is valid. |
| Validation | A check inside the setter that rejects values which do not make sense (e.g. a negative balance). |
21.2 Private Attributes & Encapsulation
- Mark scheme: Public attributes let any line of code change an object's data with no checks — that is how bugs and bad data creep in.
- Making attributes private seals them inside the class so the only way to change them is through methods you control.
- Cambridge expects you to know what encapsulation is and to write private attributes in Paper 4 answers.
- Examiner focus: Defining encapsulation was examined in
9618/32 O/N 2022 Q10(a)[3]. - The same paper asked candidates to complete an object diagram with getters and setters.
- In Paper 4,
9618/42 O/N 2021 Q2(a)required a class with private attributes [5].
In Python you make an attribute private by putting two underscores in front of its name: self.__balance. Code outside the class then cannot read or change __balance directly — it must go through a method. In Cambridge pseudocode you write the keyword PRIVATE in front of the declaration.
class BankAccount:
def __init__(self, holder, balance):
self.__holder = holder # private attribute
self.__balance = balance # private attributeThe pseudocode equivalent uses the keyword PRIVATE:
CLASS BankAccount
PRIVATE Holder : STRING
PRIVATE Balance : REAL
PUBLIC PROCEDURE NEW(GivenHolder : STRING, GivenBalance : REAL)
Holder <- GivenHolder
Balance <- GivenBalance
ENDPROCEDURE
ENDCLASSBankAccount — outside code reaches private data only through public methods
BankAccount
🔒 PRIVATE (hidden)
__holder, __balance
PUBLIC (the doorway)
get_balance()
set_balance()
deposit() withdraw()
Outside code reaches the private data only through the public methods — that is encapsulation.
- Make attributes private (
__namein Python,PRIVATEin pseudocode) and expose them only through public getter and setter methods. - This is encapsulation.
- For the definition of encapsulation, examiners want the two ideas together: data and methods are bundled inside a class, and the data is hidden from outside code.
- Giving only one half often scores only part of the mark.
21.2 Private Attributes & Encapsulation
21.3 Getter and Setter Methods
- Once data is private, you need a safe way in and out.
- A getter hands the value back; a setter changes it.
- Writing these methods is a routine Paper 4 task, and the names (
get_x,set_x) make your code self-explanatory to the examiner.
- Examiner focus: Writing get methods was examined directly in
9618/42 O/N 2021 Q2(b)[3]. - The definitions of getter and setter come straight from the mark scheme of
9618/32 O/N 2022 Q10(a): a getter returns a property; a setter updates a property.
A getter is a method that simply returns the private attribute. A setter takes a new value as a parameter and assigns it. Both reach the private attribute through self. from inside the class — which is allowed, because private only blocks access from outside.
class Person:
def __init__(self, name, age):
self.__name = name # private
self.__age = age # private
def get_name(self): # getter
return self.__name
def set_name(self, new_name): # setter
self.__name = new_name
# usage
person = Person("Mehrin", 16)
print(person.get_name()) # Mehrin
person.set_name("Nazifa")
print(person.get_name()) # Nazifa- Step 1 — getter: return the private attribute (return self.__age).
- Step 2 — setter: take a parameter and assign it to the attribute (self.__age = new_age).
- Mirror the Person example exactly.
- A getter uses
returnto hand a value back. - A setter takes the new value as a parameter and assigns it with
self.. - Both work from inside the class, where private access is allowed.
- Forgetting
returnin a getter is the most common slip — without it the method hands backNone. - The examiner is checking for
return self.__attributeexactly.
21.3 Getter and Setter Methods
21.4 Validation Inside the Setter
- The real power of a setter is that it can refuse a bad value.
- A balance should never go negative; a battery level should stay between 0 and 100.
- Putting the check inside the setter means the rule is enforced in one place, no matter who calls it — exactly the protection encapsulation promises.
Add an if inside the setter. If the value is valid, store it; otherwise leave the attribute unchanged and report the problem. The same idea powers deposit and withdraw methods, which validate before changing the balance.
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # private
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount >= 0: # validate first
self.__balance = amount # store second
else:
print("Balance cannot be negative.")
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance = self.__balance - amount
else:
print("Invalid withdrawal amount.")- The range check guards the attribute on every call: if 0 <= level <= 100.
- Same range guard as the Car.
- A setter should validate first, store second.
- If the new value breaks a rule, leave the attribute unchanged and report it — never store a value you know is invalid.
- When a question says “ensuring the balance does not become negative”, the mark is for the check (
if amount >= 0), not just the assignment. - Show the condition explicitly.
21.4 Validation Inside the Setter
21.5 Full Exam-Style Question
- A school library tracks how many books each member currently has on loan.
- A member must never hold more than five books.
(a) Define the term encapsulation. [2]
(b)(i) Write program code to declare a class Member with a constructor that takes the member's name and sets the number of books on loan to 0. Use private attributes; in Python declare each with a comment. [4]
(b)(ii) Write a getter get_books_out that returns the number of books on loan. [2]
(c) Write a method borrow() that adds 1 to the books on loan, but outputs "Limit reached" and makes no change if the member already has 5. [4]
- (a) two ideas: bundling data + methods in one class, AND hiding data from outside code.
- (b)(i) class header; constructor with self + name; private __name set; private __books_out set to 0 (with comments).
- (b)(ii) get_books_out(self) returns self.__books_out.
- (c) check if already at 5; output “Limit reached” with no change; else add 1; store back into private attribute.
21.5 Full Exam-Style Question
✓ Key Points Summary
21.6 Practice Tasks
Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
Encapsulation means:
Question 2Multiple Choice
In Python, what prefix makes an attribute private?
Question 3True / False
In pseudocode, the keyword PRIVATE in front of a declaration makes an attribute private.
Question 4Multiple Choice
A getter is a method that:
Question 5Multiple Choice
A setter is a method that:
Question 6Multiple Choice
Why make attributes private instead of public?
Question 7True / False
A getter must use return to hand a value back.
Question 8Multiple Choice
Where should validation for an attribute live?
Question 9Multiple Choice
What should a setter do if the new value is invalid?
Question 10Multiple Choice
For "Define encapsulation", examiners want:
Question 11Multiple Choice
How does a getter reach a private attribute?
Question 12True / False
A setter should validate first, store second.
Answer all 12 questions to enable submission.