🧱 Python OOP · session 1 of 12 · 60 minutes · free
Encapsulation and special functions
In Pixel's game studio a player's health, a shop's prices and a vault's code must not be changed by accident. Today you hide data inside objects, let methods guard it, and teach your classes to work with print(), len() and ==.

A complete lesson · 60 minutes
Teach it, see it, practise it, all on this page.
Open this page with your learner and work down it, or press Teach this lesson to go through it one step at a time on a big screen. Every section has something to do.
- Warm-up3 min
- Warm-up games5 min
- Private and protected attributes9 min
- Encapsulation: let methods guard the data9 min
- Special functions: __str__, __len__, __eq__9 min
- The locked diary7 min
- Game shop price guard7 min
- Treasure map points5 min
- Quiz5 min
- Set the after-class project1 min
By the end you can
- Tell public, protected (_name) and private (__name) attributes apart
- Explain name mangling and why outside code gets AttributeError
- Change private data only through methods that check it (setters)
- Write __str__, __repr__, __len__ and __eq__ so objects work with print(), len() and ==
Before you start
- Writing a class with __init__ and self
- Creating objects and calling methods
- if, loops and f-strings
Have ready
- This page (the code runs in the browser)
- Paper to plan a class: its data and its methods
Grades 9 and 10 · ages 14 to 16 · after a first Python course
Warm-up · think first
A game stores a player's coins as player.coins. Any line of code anywhere can write player.coins = 999999. What could go wrong, and how would you stop it?
Show the answer
Anyone can cheat or make a mistake: coins can become negative or huge. Keep coins inside the object and change them only through methods like earn() and spend() that check the numbers. That is encapsulation.
Teacher tip: Collect ideas, then say: today we build exactly that protection.
🎮 Warm-up games · 5 quick games
Play with Bolt the robot
Five minutes in Pixel's game studio. Vote, say why, then show the answer.
- Which one is not something a game object should guard? (Health points · Coins · Password · Display colour)
Answer: The player's chosen display colour is harmless to change. Health, coins and a password all need rules. - A double underscore, like self.__code, makes an attribute completely impossible to reach. (Always · Sometimes · Never)
Answer: Sometimes — Sometimes. Python renames it to _Vault__code, so it is hidden from mistakes, not locked against someone determined. - Would you rather set a player's health directly, or call take_damage(10)? (player.health = 90 · player.take_damage(10))
Answer: take_damage(10) can stop health going below 0 and can play a sound. Direct access can't check anything. - print(len("game")) shows 4. What do you think print(len(my_playlist)) shows, if my_playlist is your own object?
Answer: An error, unless the class says what its length is. Part 3 teaches __len__ to do exactly that. - Name three things in a real app that should only change through a button or a check, never directly.
Answer: Bank balances, passwords, exam marks, stock in a shop. Each needs rules: that is what methods are for.
Three levels, like a real engineer
Use it. Tweak it. Build it.
First use what the lesson shows exactly as it is, then change one key thing and see what happens, then make your own.
- 🔒
Level 1 · Use it
Run the PiggyBank
Run this exact PiggyBank class: __balance starts at 10, add_coins(5) raises it, and __str__ prints PiggyBank with 15 coins. Then type piggy.__balance and watch the AttributeError appear.
- 🔧
Level 2 · Tweak it
Change the numbers
In that same PiggyBank, change the starting __balance from 10 to 25, and change add_coins(5) to add_coins(20). Before running, predict the new balance and the new __str__ text.
- 🛠️
Level 3 · Build it
Build your Robot
Make your own Robot class with a private __power of 50, a charge(amount) method that refuses amounts over 100, plus __str__ and __len__. Test print(robot), len(robot) and robot.__power.
🗺️ Play the Lesson QuestThree worlds, one for each level, with short stages that bring back what you miss.
Part 1 of 3 · learn, see, practise
Private and protected attributes
Pixel here, lead programmer. Our vault object holds a secret code. If any line of code can read it, it isn't secret. Python gives us two signals: one underscore says please don't touch, two underscores hide the name.
A name with no underscore is public: anyone can read and change it. One underscore, like self._level, is protected: a polite sign meaning inside use only. Python still allows access.
Two underscores, like self.__code, make an attribute private. Inside the class Python quietly renames it to _Vault__code (name mangling), so obj.__code from outside fails with AttributeError.
Mangling stops accidents, not a determined person: obj._Vault__code still works. It also works for methods, like def __shuffle(self), and class variables.
🧑🏫 Teacher: type this live with the class
Build the vault
class Vault:A class is a blueprint. Ask: what data does a vault need?
def __init__(self, code):__init__ runs when we make a vault. Four spaces in.
self.__code = codeTwo underscores: a private attribute. Eight spaces in.
self._owner = "Pixel"One underscore: protected, a polite sign.
v = Vault(4321)Make a vault. Back at the left edge.
print(v._owner)Run it. Protected is only a sign: it prints.
print(v._Vault__code)The renamed private attribute. Ask: why does this work? Then show print(v.__code) fails.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
Aria 1 50
📦 Memory boxes
<class '__main__.Player'>typep<__main__.Player object at 0x7f3a2c40>PlayerRun it. Then take the # off the last line and run again: AttributeError. Now try print(p._Player__coins) instead.
Puzzle break: what does Python do?
Hands off the keyboard. Decide what happens before anyone presses Run.
- Puzzle 1: say what happens before you run it
- Puzzle 2: say what happens before you run it
- Puzzle 3: fill the gap
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
1.1 The class keeps coins in a private attribute. Finish get_coins so it returns them, then print get_coins() for p.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Player'>typep<__main__.Player object at 0x7f3a2c70>Player🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Player: def __init__(self): self.__coins = 50 def get_coins(self): return self.__coins p = Player()print(p.get_coins())
What it prints
50
What ✓ Check looks for
- it prints exactly:
50
- In the code: Return self.__coins inside the method.
1.2 Print the player's protected level, then make it 2 and print it again. (Protected is only a sign: Python allows it.)
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Player'>typep<__main__.Player object at 0x7f3a2ca0>Player🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
class Player: def __init__(self): self._level = 1 p = Player()print(p._level)p._level = 2print(p._level)
What it prints
1 2
What ✓ Check looks for
- it prints exactly:
1 2
- In the code: Set p._level = 2.
1.3 Python renamed self.__code. Print the vault's code from outside by using its renamed attribute.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Vault'>typev<__main__.Vault object at 0x7f3a2cd0>Vault🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 1 line the student writes
class Vault: def __init__(self, code): self.__code = code def check(self, guess): return guess == self.__code v = Vault(4321)print(v._Vault__code)
What it prints
4321
What ✓ Check looks for
- it prints exactly:
4321
- In the code: The renamed attribute is _Vault__code.
1.4 Add a method can_buy(self, price) that returns True when the private coins are at least price. Print can_buy(30) and can_buy(80) on two lines.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Player'>typep<__main__.Player object at 0x7f3a2d00>Player🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
class Player: def __init__(self): self.__coins = 50 def can_buy(self, price): return self.__coins >= price p = Player()print(p.can_buy(30))print(p.can_buy(80))
What it prints
True False
What ✓ Check looks for
- it prints exactly:
True False
- In the code: Write def can_buy(self, price):
- In the code: Compare self.__coins >= price.
1.5 Fix the bug so it prints Secret: dragon. The attribute is private but the method uses the wrong name.
▶ Output
Line 6: AttributeError: 'Note' object has no attribute 'text'
📦 Memory boxes
<class '__main__.Note'>typen<__main__.Note object at 0x7f3a2d30>Note🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 1 line the student writes
class Note: def __init__(self, text): self.__text = text def read(self): return "Secret: " + self.__text n = Note("dragon")print(n.read())
What it prints
Secret: dragon
What ✓ Check looks for
- it prints exactly:
Secret: dragon
- In the code: Inside the class the private name is self.__text.
1.6 Prove what name mangling does: use hasattr to print whether c has an attribute called "__pin", then whether it has "_Card__pin". (Expect False, then True.)
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Card'>typec<__main__.Card object at 0x7f3a2d60>Card🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Card: def __init__(self): self.__pin = 1234 c = Card()print(hasattr(c, "__pin"))print(hasattr(c, "_Card__pin"))
What it prints
False True
What ✓ Check looks for
- it prints exactly:
False True
- In the code: Use hasattr(c, "...").
Part 2 of 3 · learn, see, practise
Encapsulation: let methods guard the data
Bug report from testers: a shield's strength went to minus 40. Fix: nobody sets strength directly any more. They call methods, and the methods check the numbers first.
Encapsulation means keeping the data and the methods that use it together in one class, and changing the data only through those methods.
A getter returns a private value; a setter changes it after checking it. A setter that refuses bad values keeps every object valid.
Outside code that writes obj.__value = 5 does not touch the private attribute: it makes a new, separate attribute. The object's own methods keep using the real one.
🧑🏫 Teacher: type this live with the class
A shield that can't break the rules
class Shield:A new class.
def __init__(self):Start every shield at full strength.
self.__strength = 100Private, so outside code can't set it by accident.
def hit(self, damage):The only way to lower strength.
self.__strength = max(0, self.__strength - damage)max(0, …) never lets it fall below 0. Ask why.
def strength(self):A getter.
return self.__strengthReturn the private value.
s = Shield()Make a shield.
s.hit(130)Too much damage on purpose.
print(s.strength())Run: 0, not -30. The method guarded it.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
Price: 120 Price: 120 Refused: a price must be more than 0 Price: 150
📦 Memory boxes
<class '__main__.Shop'>typeshop<__main__.Shop object at 0x7f3a2d90>ShopTrace it line by line before running. Why does shop.__price = 5 change nothing? Then try shop.set_price(0).
Puzzle break: guard the data
Read the code the way Python does, line by line, before running anything.
- Puzzle 1: say what happens before you run it
- Puzzle 2: find the bug
- Puzzle 3: fill the gap
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
2.1 Finish deposit so it adds amount to the private balance. Deposit 50 and print balance().
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Account'>typea<__main__.Account object at 0x7f3a2dc0>Account🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
class Account: def __init__(self): self.__balance = 100 def deposit(self, amount): self.__balance += amount def balance(self): return self.__balance a = Account()a.deposit(50)print(a.balance())
What it prints
150
What ✓ Check looks for
- it prints exactly:
150
- In the code: Add to self.__balance inside deposit.
2.2 Add a getter name(self) that returns the private name, and print it for Kai.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Hero'>typeh<__main__.Hero object at 0x7f3a2df0>Hero🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
class Hero: def __init__(self, name): self.__name = name def name(self): return self.__name h = Hero("Kai")print(h.name())
What it prints
Kai
What ✓ Check looks for
- it prints exactly:
Kai
- In the code: Write def name(self):
2.3 Write set_age(self, age): if age is below 0, print Age can't be negative and keep the old age; otherwise store it. Then run the three lines at the bottom.
▶ Output
Line 11: AttributeError: 'Pet' object has no attribute 'set_age'
📦 Memory boxes
<class '__main__.Pet'>typepet<__main__.Pet object at 0x7f3a2e20>Pet🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 5 lines the student writes
class Pet: def __init__(self): self.__age = 1 def age(self): return self.__age def set_age(self, age): if age < 0: print("Age can't be negative") else: self.__age = age pet = Pet()pet.set_age(-4)pet.set_age(3)print(pet.age())
What it prints
Age can't be negative 3
What ✓ Check looks for
- it prints exactly:
Age can't be negative 3
- In the code: Write def set_age(self, age):
2.4 Write withdraw(self, amount): take the money out only if there is enough, and return True; otherwise return False. Print the three results.
▶ Output
Line 8: AttributeError: 'Wallet' object has no attribute 'withdraw'
📦 Memory boxes
<class '__main__.Wallet'>typew<__main__.Wallet object at 0x7f3a2e50>Wallet🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 5 lines the student writes
class Wallet: def __init__(self): self.__cash = 60 def withdraw(self, amount): if amount <= self.__cash: self.__cash -= amount return True return False w = Wallet()print(w.withdraw(50))print(w.withdraw(20))print(w.withdraw(10))
What it prints
True False True
What ✓ Check looks for
- it prints exactly:
True False True
- In the code: Return False when there isn't enough.
2.5 A thermostat keeps a private temperature between 16 and 30. up() and down() change it by 2 but never leave that range. After the moves below it must print 30, then 16.
▶ Output
24 24
📦 Memory boxes
<class '__main__.Thermostat'>typet<__main__.Thermostat object at 0x7f3a2e80>Thermostati8int🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Thermostat: def __init__(self): self.__temp = 24 def up(self): self.__temp = min(30, self.__temp + 2) def down(self): self.__temp = max(16, self.__temp - 2) def temp(self): return self.__temp t = Thermostat()for i in range(5): t.up()print(t.temp())for i in range(9): t.down()print(t.temp())
What it prints
30 16
What ✓ Check looks for
- it prints exactly:
30 16
- In the code: Check the limits with if, min() or max().
2.6 A lock allows 3 wrong guesses. try_code(guess) returns "Open" for the right code, "Wrong" for a wrong one, and "Locked" for every guess after the third wrong one (even the right code). Keep the code and the count private.
▶ Output
None None None None None None
📦 Memory boxes
<class '__main__.Lock'>typelock<__main__.Lock object at 0x7f3a2eb0>Lockg2580int🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
class Lock: def __init__(self, code): self.__code = code self.__wrong = 0 def try_code(self, guess): if self.__wrong >= 3: return "Locked" if guess == self.__code: return "Open" self.__wrong += 1 return "Wrong" lock = Lock(2580)for g in [1111, 2580, 3, 4, 5, 2580]: print(lock.try_code(g))
What it prints
Wrong Open Wrong Wrong Locked Locked
What ✓ Check looks for
- it prints exactly:
Wrong Open Wrong Wrong Locked Locked
- In the code: Count wrong guesses in self.__wrong.
Part 3 of 3 · learn, see, practise
Special functions: __str__, __len__, __eq__
Our objects print as <__main__.Song object at 0x…>. Ugly! Special functions, the ones wrapped in double underscores on both sides, let our classes work with print(), len() and == like Python's own types.
Special functions (also called magic or dunder methods) start and end with two underscores. Python calls them for you: __init__ when an object is made, __str__ when it is printed.
__str__ returns the friendly text for print() and f-strings; __repr__ returns the text shown inside lists and for debugging. __len__ returns a whole number for len().
__eq__(self, other) decides what == means. Without it, two objects are equal only if they are the very same object. Names with two underscores at both ends are never mangled.
🧑🏫 Teacher: type this live with the class
A song that prints itself
class Song:A class for a song.
def __init__(self, title, seconds):Two things to store.
self.title = titlePublic is fine here.
self.seconds = secondsdef __str__(self):print() calls this for us.
return f"{self.title} ({self.seconds // 60}:{self.seconds % 60:02d})"Minutes and seconds, with :02d for 3:05.
def __len__(self):len() calls this. It must return a whole number.
return self.secondss = Song("Level Up", 185)Make a song.
print(s)Run: Level Up (3:05).
print(len(s))Run: 185.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
Ace of Spades
[Card('Ace', 'Spades'), Card('Ace', 'Spades')]
True📦 Memory boxes
<class '__main__.Card'>typeaCard('Ace', 'Spades')CardbCard('Ace', 'Spades')CardDelete __eq__ and run again: a == b becomes False, because they are two separate objects.
Puzzle break: special functions
Read the code the way Python does, line by line, before running anything.
- Puzzle 1: say what happens before you run it
- Puzzle 2: find the bug
- Puzzle 3: fill the gap
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
3.1 Add __str__ so print(h) shows Kai (level 3).
▶ Output
<__main__.Hero object at 0x7f3a2ee0>
📦 Memory boxes
<class '__main__.Hero'>typeh<__main__.Hero object at 0x7f3a2ee0>Hero🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Hero: def __init__(self, name, level): self.name = name self.level = level def __str__(self): return f"{self.name} (level {self.level})" h = Hero("Kai", 3)print(h)
What it prints
Kai (level 3)
What ✓ Check looks for
- it prints exactly:
Kai (level 3)
- In the code: Write def __str__(self): and return the text.
3.2 Add __len__ so len(p) is the number of songs in the playlist.
▶ Output
Line 8: TypeError: object of type 'Playlist' has no len()
📦 Memory boxes
<class '__main__.Playlist'>typep<__main__.Playlist object at 0x7f3a2f10>Playlist🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Playlist: def __init__(self, songs): self.songs = songs def __len__(self): return len(self.songs) p = Playlist(["Intro", "Boss fight", "Victory"])print(len(p))
What it prints
3
What ✓ Check looks for
- it prints exactly:
3
- In the code: Write def __len__(self):
- With
p = Playlist(["A", "B"]), it prints exactly:2
3.3 Add __eq__ so two points are equal when both x and y match. Print the two comparisons.
▶ Output
False False
📦 Memory boxes
<class '__main__.Point'>type🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y print(Point(2, 3) == Point(2, 3))print(Point(2, 3) == Point(3, 2))
What it prints
True False
What ✓ Check looks for
- it prints exactly:
True False
- In the code: Write def __eq__(self, other):
3.4 Add __repr__ so the list prints as [Point(1, 2), Point(5, 0)].
▶ Output
[<__main__.Point object at 0x7f3a2f40>, <__main__.Point object at 0x7f3a2f70>]
📦 Memory boxes
<class '__main__.Point'>type🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" print([Point(1, 2), Point(5, 0)])
What it prints
[Point(1, 2), Point(5, 0)]
What ✓ Check looks for
- it prints exactly:
[Point(1, 2), Point(5, 0)]
- In the code: Lists use __repr__, not __str__.
3.5 Make Coins add up with +: add __add__ that returns a NEW Coins with both amounts, and __str__ that shows like 75 coins.
▶ Output
Line 7: TypeError: unsupported operand type(s) for +: 'Coins' and 'Coins'
📦 Memory boxes
<class '__main__.Coins'>type🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
class Coins: def __init__(self, amount): self.amount = amount def __add__(self, other): return Coins(self.amount + other.amount) def __str__(self): return f"{self.amount} coins" print(Coins(30) + Coins(45))
What it prints
75 coins
What ✓ Check looks for
- it prints exactly:
75 coins
- In the code: Write def __add__(self, other):
- In the code: __add__ should return a new Coins object.
3.6 Add __lt__ (less than) comparing scores, so sorted() puts players in order. Then print their names from lowest to highest score, one per line.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Player'>typeteam[<__main__.Player object at 0x7f3a2fa0>, <__main__.Player object at 0x7f3a2fd0>, <__main__.Player object at 0x7f3a3000>]list🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
class Player: def __init__(self, name, score): self.name = name self.score = score def __lt__(self, other): return self.score < other.score team = [Player("Ana", 70), Player("Ben", 45), Player("Cy", 90)]for p in sorted(team): print(p.name)
What it prints
Ben Ana Cy
What ✓ Check looks for
- it prints exactly:
Ben Ana Cy
- In the code: Write def __lt__(self, other):
- In the code: Use sorted(team).
Watch out
Common mistakes
Thinking one underscore hides anything
self._level is only a polite sign. Python lets anyone read and change it.
Expecting obj.__x = 5 to change the private value
Outside the class it makes a brand-new attribute. The object's methods keep using the real one.
Using the private name in another class
Inside class Child, self.__p means _Child__p, not the parent's _Base__p. Give the parent a method instead.
Printing in __str__ instead of returning
__str__ must return a string. If it prints and returns nothing, print(obj) stops with a TypeError.
Returning a float or text from __len__
len() needs a whole number from __len__.
Class activity 1 of 3
The locked diary
Build a diary that keeps its entries private. Only write() can add to it, every entry gets a day number from a private helper, and outside code that tries to read the list is stopped. When it works it prints:
Day 1: Found the hidden level
Day 2: Beat the ice boss
Locked! Use read() instead.
- Make the list and the day counter private in __init__.
- Write the private helper __stamp(self, text): add 1 to the counter and return "Day N: text".
- write(text) adds __stamp(text) to the list; read() prints every entry.
- At the bottom, try to print diary.__entries inside try/except AttributeError and print the locked message.
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Diary'>typediary<__main__.Diary object at 0x7f3a3030>DiaryHint
Inside the class, call the helper as self.__stamp(text). Outside, diary.__entries raises AttributeError because the real name is _Diary__entries.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 17 lines the student writes
# ===== The locked diary =====class Diary: def __init__(self): self.__entries = [] self.__day = 0 def __stamp(self, text): self.__day += 1 return f"Day {self.__day}: {text}" def write(self, text): self.__entries.append(self.__stamp(text)) def read(self): for entry in self.__entries: print(entry) diary = Diary()diary.write("Found the hidden level")diary.write("Beat the ice boss")diary.read() try: print(diary.__entries)except AttributeError: print("Locked! Use read() instead.")
What it prints
Day 1: Found the hidden level Day 2: Beat the ice boss Locked! Use read() instead.
What ✓ Check looks for
- it prints exactly:
Day 1: Found the hidden level Day 2: Beat the ice boss Locked! Use read() instead.
- In the code: Step 2: write the private helper def __stamp(self, text):
- In the code: Step 1: keep the entries in self.__entries.
- In the code: Step 6: catch AttributeError.
If they're stuck, say
Inside the class, call the helper as self.__stamp(text). Outside, diary.__entries raises AttributeError because the real name is _Diary__entries.
Class activity 2 of 3
Game shop price guard
A shop item's price is private. Prove that outside code can't change it by accident, and that the setter refuses silly prices. When it works it prints:
Laser sword costs 120 coins
Laser sword costs 120 coins
Refused: a price must be more than 0
Laser sword costs 150 coins
- Store the name (public) and the price (private) in __init__.
- show() prints the name and price.
- set_price(price) refuses a price of 0 or less with the message, otherwise stores it.
- Follow the numbered calls at the bottom and read the output: which line made a new attribute instead?
▶ Output
(nothing is printed)
📦 Memory boxes
<class '__main__.Item'>typesword<__main__.Item object at 0x7f3a3060>ItemHint
sword.__price = 1 from outside makes a new attribute called __price. show() reads the real one, _Item__price, so nothing changes.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 12 lines the student writes
# ===== Game shop price guard =====class Item: def __init__(self, name, price): self.name = name self.__price = price def show(self): print(f"{self.name} costs {self.__price} coins") def set_price(self, price): if price <= 0: print("Refused: a price must be more than 0") else: self.__price = price sword = Item("Laser sword", 120)sword.show()sword.__price = 1sword.show()sword.set_price(-5)sword.set_price(150)sword.show()
What it prints
Laser sword costs 120 coins Laser sword costs 120 coins Refused: a price must be more than 0 Laser sword costs 150 coins
What ✓ Check looks for
- it prints exactly:
Laser sword costs 120 coins Laser sword costs 120 coins Refused: a price must be more than 0 Laser sword costs 150 coins
- In the code: Step 1 and 3: store the price in self.__price.
- In the code: Step 4: try sword.__price = 1 from outside.
If they're stuck, say
sword.__price = 1 from outside makes a new attribute called __price. show() reads the real one, _Item__price, so nothing changes.
Class activity 3 of 3
Treasure map points
Map spots should print nicely, compare with == and know how far apart they are (steps along the grid, no diagonals). When it works it prints:
Treasure at (3, 7)
Camp at (0, 1)
Same spot? False
Same spot? True
Steps to the treasure: 9
- __init__ stores x and y.
- __str__ returns (x, y).
- __eq__ compares both coordinates.
- steps_to(other) returns abs(dx) + abs(dy). Then follow the prints at the bottom.
▶ Output
Treasure at <__main__.Spot object at 0x7f3a3090> Camp at <__main__.Spot object at 0x7f3a30c0> Same spot? False Same spot? False Line 20: AttributeError: 'Spot' object has no attribute 'steps_to'
📦 Memory boxes
<class '__main__.Spot'>typetreasure<__main__.Spot object at 0x7f3a3090>Spotcamp<__main__.Spot object at 0x7f3a30c0>SpotHint
abs() makes a negative difference positive, so the steps are the same in both directions.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 8 lines the student writes
# ===== Treasure map points =====class Spot: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({self.x}, {self.y})" def __eq__(self, other): return self.x == other.x and self.y == other.y def steps_to(self, other): return abs(self.x - other.x) + abs(self.y - other.y) treasure = Spot(3, 7)camp = Spot(0, 1)print(f"Treasure at {treasure}")print(f"Camp at {camp}")print("Same spot?", treasure == camp)print("Same spot?", treasure == Spot(3, 7))print("Steps to the treasure:", camp.steps_to(treasure))
What it prints
Treasure at (3, 7) Camp at (0, 1) Same spot? False Same spot? True Steps to the treasure: 9
What ✓ Check looks for
- it prints exactly:
Treasure at (3, 7) Camp at (0, 1) Same spot? False Same spot? True Steps to the treasure: 9
- With
treasure = Spot(-2, 4), it prints exactly:Treasure at (-2, 4) Camp at (0, 1) Same spot? False Same spot? False Steps to the treasure: 5
- In the code: Step 3: write __eq__.
If they're stuck, say
abs() makes a negative difference positive, so the steps are the same in both directions.
After class · project
My game hero class
Design a Hero for your own game. Health is private and must stay between 0 and 100. take_hit() and heal() are the only ways to change it, the hero prints nicely, and two heroes can be compared by health.
What to make: A Hero class with private health that stays between 0 and 100, a __str__, a __lt__ and a short battle that prints at least four lines.
Stretch: Add a private __shield that soaks up the first 20 damage of every hit, and a __len__ that returns how many hits the hero has taken.
How it is marked
| Look for | Done well when |
|---|---|
| Runs | No red error when you press Run |
| Private | Health is private and only changed by take_hit() and heal() |
| Limits | Health never goes below 0 or above 100 |
| Special functions | __str__ prints the hero; __lt__ compares two heroes |
| Battle | A short battle prints the hero after each move |
Starter code to take home
Press Copy and paste it into the editor at home, or work on it right here.
▶ Output
<__main__.Hero object at 0x7f3a30f0>
📦 Memory boxes
<class '__main__.Hero'>typenova<__main__.Hero object at 0x7f3a30f0>Hero🔑 Show one possible solution (try it yourself first!)
▶ Output
Nova (30/100) Nova (100/100) Nova (0/100) False True
📦 Memory boxes
<class '__main__.Hero'>typenova<__main__.Hero object at 0x7f3a3120>Herorex<__main__.Hero object at 0x7f3a3150>HeroHomework
Practise at home
Each one checks itself. Or print the practice sheet.
1. Make a class Box with a private __items list and a method count() that returns how many items it holds. Add 2 items in __init__ (any you like) and print count().
▶ Output
(nothing is printed)
📦 Memory boxes
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
class Box: def __init__(self): self.__items = ["key", "map"] def count(self): return len(self.__items) print(Box().count())
What it prints
2
What ✓ Check looks for
- it prints exactly:
2
- In the code: Keep the items in self.__items.
- In the code: Write def count(self):
2. Give Temperature a setter set_celsius(c) that refuses anything below -273 (print Too cold!) and a getter fahrenheit() that returns c * 9 / 5 + 32. Run the lines at the bottom.
▶ Output
Line 8: AttributeError: 'Temperature' object has no attribute 'set_celsius'
📦 Memory boxes
<class '__main__.Temperature'>typet<__main__.Temperature object at 0x7f3a3180>Temperature🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 7 lines the student writes
class Temperature: def __init__(self): self.__c = 0 def set_celsius(self, c): if c < -273: print("Too cold!") else: self.__c = c def fahrenheit(self): return self.__c * 9 / 5 + 32 t = Temperature()t.set_celsius(-300)t.set_celsius(100)print(t.fahrenheit())
What it prints
Too cold! 212.0
What ✓ Check looks for
- it prints exactly:
Too cold! 212.0
- In the code: Write def set_celsius(self, c):
3. Add __str__ and __len__ to Word so print(w) shows the word in capitals and len(w) counts its letters. For Word("pixel") print PIXEL, then 5.
▶ Output
<__main__.Word object at 0x7f3a31b0> Line 7: TypeError: object of type 'Word' has no len()
📦 Memory boxes
<class '__main__.Word'>typew<__main__.Word object at 0x7f3a31b0>Word🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
class Word: def __init__(self, text): self.text = text def __str__(self): return self.text.upper() def __len__(self): return len(self.text) w = Word("pixel")print(w)print(len(w))
What it prints
PIXEL 5
What ✓ Check looks for
- it prints exactly:
PIXEL 5
- In the code: Add __str__.
- In the code: Add __len__.
4. Fraction: add __str__ (like 3/4) and __eq__ so Fraction(1, 2) == Fraction(2, 4) is True (compare a/b and c/d by cross-multiplying: a * d == c * b). Print the fraction and both comparisons.
▶ Output
<__main__.Fraction object at 0x7f3a31e0> False False
📦 Memory boxes
<class '__main__.Fraction'>type🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
class Fraction: def __init__(self, top, bottom): self.top = top self.bottom = bottom def __str__(self): return f"{self.top}/{self.bottom}" def __eq__(self, other): return self.top * other.bottom == other.top * self.bottom print(Fraction(3, 4))print(Fraction(1, 2) == Fraction(2, 4))print(Fraction(1, 2) == Fraction(2, 3))
What it prints
3/4 True False
What ✓ Check looks for
- it prints exactly:
3/4 True False
- In the code: Add __eq__.
5. A Stack keeps a private list. push(x) adds to the end, pop() removes and returns the last item (or None when empty), and __len__ gives the size. Run the lines at the bottom.
▶ Output
Line 8: AttributeError: 'Stack' object has no attribute 'push'
📦 Memory boxes
<class '__main__.Stack'>types<__main__.Stack object at 0x7f3a3210>Stack🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 8 lines the student writes
class Stack: def __init__(self): self.__items = [] def push(self, x): self.__items.append(x) def pop(self): if not self.__items: return None return self.__items.pop() def __len__(self): return len(self.__items) s = Stack()s.push("a")s.push("b")print(s.pop())print(len(s))print(s.pop())print(s.pop())
What it prints
b 1 a None
What ✓ Check looks for
- it prints exactly:
b 1 a None
- In the code: Use the private list.
- In the code: Add __len__.
🔥 Challenge round · finished early?
The hardest questions of the lesson, no notes
Cover the notes and try these from memory. They are meant to make you think hard: draw, try small cases, and check your answer.
- Stretch task 1: Fix the bug so it prints Secret: dragon. The attribute is private but the method uses the wrong name.
- Stretch task 1: Prove what name mangling does: use hasattr to print whether c has an attribute called "__pin", then whether it has "_Card__pin". (Expect False, then True.)
- Stretch task 2: A thermostat keeps a private temperature between 16 and 30. up() and down() change it by 2 but never leave that range. After the moves below it must print 30, then 16.
- Stretch task 2: A lock allows 3 wrong guesses. try_code(guess) returns "Open" for the right code, "Wrong" for a wrong one, and "Locked" for every guess after the third wrong one (even the right code). Keep the code and the count private.
- Stretch task 3: Make Coins add up with +: add __add__ that returns a NEW Coins with both amounts, and __str__ that shows like 75 coins.
- Stretch task 3: Add __lt__ (less than) comparing scores, so sorted() puts players in order. Then print their names from lowest to highest score, one per line.
🧠 Think-hard question
Write a BankAccount whose balance is private and a transfer(other, amount) method that moves money between two accounts only if there is enough. Two accounts can read each other's private balance inside the class. Why is that allowed?
Talk it through or use the drawing board. There is more than one way to get there.
Quiz · 8 questions
Final quiz: check what you learned
Pick an answer to see if it is right and why. Your best score is saved on this device.
🖨 Print what we learned
Make a worksheet from this lesson
Pick what to practise, then print it or choose Save as PDF in the print window to download it.
For parents and teachers
The 60-minute lesson plan
Use it as it is, or stretch any part over two sessions. Each row links to the part of the page you need.
| Time | Part | The teacher | The learner |
|---|---|---|---|
| 0–3 min | Warm-up | Ask the question and wait for a guess before any hint. | Guess, then explain. |
| 3–8 min | Warm-up games | Play three or four games. Ask for a reason each time. | Vote and say why. |
| 8–17 min | Private and protected attributes | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 17–26 min | Encapsulation: let methods guard the data | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 26–35 min | Special functions: __str__, __len__, __eq__ | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 35–42 min | The locked diary | Show the boilerplate and read the numbered steps. Let them press Check often. | Follow the steps. |
| 42–49 min | Game shop price guard | Do step 1 together, then let them finish. | Finish the activity. |
| 49–54 min | Treasure map points | If time is short, set it as homework. | Try the challenge. |
| 54–59 min | Quiz | Read each question aloud. Vote, then check. | Answer and read why. |
| 59–60 min | Set the after-class project | Open the project and agree a due date. | Copy the boilerplate. |
Questions to ask
- What is the difference between _level and __level?
- Why does obj.__price = 5 outside the class not change the real price?
- Which special function does print() use, and which does a list use?
- Why is a setter safer than changing an attribute directly?
If it feels hard
Draw an object as a box with two windows: public attributes on the outside, private ones inside with a lock, and methods as the only doors. Trace each line of the shop example on paper before running it.
If it feels easy
Write a BankAccount whose balance is private and a transfer(other, amount) method that moves money between two accounts only if there is enough. Two accounts can read each other's private balance inside the class. Why is that allowed?
FAQ
Encapsulation and special functions: questions
What is encapsulation in Python?
Keeping an object's data and the methods that use it together, and changing the data only through those methods, so the object can check every change.
Are private attributes really private in Python?
No. Two underscores rename the attribute (name mangling) so outside code can't use it by accident, but _ClassName__name still reaches it. Python trusts programmers.
What are special functions?
Methods with two underscores at both ends, like __init__, __str__, __len__ and __eq__. Python calls them for you when you create, print, measure or compare objects.
Start a conversation
Want a teacher to take this class?
Tell us the learner's age and level. A teacher from our network teaches with these lessons; we confirm timing and price first.
- Tell us the learner’s age or grade and goals
- We’ll suggest a suitable class or learning path
- We’ll confirm format, timing and fees with a parent or guardian