Module 15 · Lesson 03
Encapsulation and Properties
Protect an object's data the Python way: underscore conventions, name mangling, and @property for computed, validated and read-only attributes that callers still use like plain attributes.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Underscore by agreement
- Read like an attribute
- A setter that checks
- Watch a setter tidy a name
Guard your data, keep it easy to use
Python protects data by agreement and by properties, not by locking it away.
_internal
One underscore says "internal, please do not touch". Nothing stops you.
__mangled
Two underscores rename the attribute per class, to avoid clashes in subclasses.
@property
A method you read like an attribute:
box.area, with no brackets.Setters
@x.setterruns code on every assignment, so bad values can be fixed or refused.
Properties everywhere
Wherever a value must stay valid, a property can guard it.
- Bank balancesA read-only balance changes only through deposit and withdraw.
- Health barsA setter keeps a player's health between 0 and 100.
- UnitsStore a distance in metres once and show kilometres as a property.
- UsernamesA setter strips spaces and refuses an empty name.
The line inside a setter
This setter line keeps health between 0 and 100. Tap each part to see its job.
Part 1 of 4
stored value:The real value lives under an underscore name, so it does not clash with the property called health.
Attributes with code behind them
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Underscore by agreement
The underscore is a sign for people. Python still lets you read and change it.
Your turn: Rename _secret to __secret in the class and run again. What happens to r.__secret?
class Recipe:
def __init__(self, name):
self.name = name
self._secret = "a pinch of salt"
r = Recipe("soup")
print(r.name)
print(r._secret)
r._secret = "sugar"
print(r._secret)Press Run to see what it prints.Watch a setter tidy a name
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- class User:
- def __init__(self, name):
- self.name = name
- def name(self):
- return self._name
- def name(self, value):
- self._name = value.strip().title()
- u = User(" ana lee ")
- print(u.name)
- u.name = "BEN"
- print(u.name)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Reading an underscore name:
class A:
def __init__(self):
self._code = 7
print(A()._code)0 of 6 answered
Common property misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
self._internal = value # convention: internal
self.__mangled = value # becomes self._ClassName__mangled
class Thing:
def __init__(self, size):
self.size = size # runs the setter
@property
def size(self): # read: thing.size
return self._size
@size.setter
def size(self, value): # write: thing.size = value
if value < 0:
raise ValueError("size must be >= 0")
self._size = value
@property
def double(self): # no setter: read-only
return self._size * 2
from functools import cached_property # compute once, then storePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A bank account with a read-only balance
Write an Account whose balance can be read but not assigned, and only changes through deposit and withdraw, which refuse amounts that are not positive and withdrawals that would overdraw.
class Account:
def __init__(self, owner):
self.owner = owner
self._balance = 0
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self._balance:
raise ValueError(f"only {self._balance} available")
self._balance -= amount
acc = Account("Mia")
acc.deposit(100)
acc.withdraw(30)
print(acc.owner, acc.balance)
for action in [lambda: acc.withdraw(500), lambda: acc.deposit(-5)]:
try:
action()
except ValueError as error:
print("refused:", error)
try:
acc.balance = 1_000_000
except AttributeError:
print("balance cannot be assigned directly")
print("still", acc.balance)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Using the property name inside its own setter
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
class Pet:
@property
def name(self):
return self.name
print(Pet().name)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- E-commerce
Order lines that keep their totals honest
A shop's checkout shows each order line's quantity, price, discount and total. Bugs used to appear when one value was updated and the total was not. Now quantity and discount are validated properties and the total is computed, so the numbers on screen always agree.
Why Python fits
The total is never stored, so it cannot drift from the quantity and discount. Both inputs are checked by their setters, including the starting quantity passed to
__init__. The checkout code just reads and assigns attributes; all the rules live in the class.Pythonclass OrderLine: MAX_DISCOUNT = 50 def __init__(self, product, unit_cents, quantity=1): self.product = product self._unit_cents = unit_cents self.quantity = quantity self.discount = 0 @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): if not 1 <= value <= 99: raise ValueError("quantity must be 1 to 99") self._quantity = value @property def discount(self): return self._discount @discount.setter def discount(self, percent): if not 0 <= percent <= self.MAX_DISCOUNT: raise ValueError(f"discount must be 0 to {self.MAX_DISCOUNT}%") self._discount = percent @property def total_cents(self): gross = self._unit_cents * self._quantity return gross - gross * self._discount // 100 line = OrderLine("headphones", 4999, quantity=2) print(line.product, line.quantity, line.total_cents) line.discount = 20 line.quantity = 3 print(line.product, line.quantity, line.total_cents) for change in [lambda: setattr(line, "quantity", 0), lambda: setattr(line, "discount", 75)]: try: change() except ValueError as error: print("refused:", error) print("total still", line.total_cents)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Should I write a property for every attribute?
Can a property take arguments?
Where does the real value live when I use a property?
Is there a way to delete a property?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 17 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.