Python Encapsulation and Properties
What you will learn
- What encapsulation means, and why it helps
- Python's naming conventions:
_internaland__private @property: read-only, validated and computed attributes- Setters and deleters
cached_propertyfor expensive values- Protecting lists and dictionaries inside an object
1. Encapsulation
Encapsulation means an object keeps its data to itself and lets the outside world work with it only through well-defined methods. This protects the data from bad changes and lets you change how it is stored later without breaking the programs that use the class.
Look at what can go wrong with a plain attribute:
class Temp2:
def __init__(self, c):
self.c = c
t = Temp2(20)
t.c = -9999
print(t.c)
-9999
Nothing stopped a temperature far below absolute zero (about -273.15 degrees Celsius). A class can guard its data, so that invalid states can never happen.
Quick check: what is the main benefit of protecting an object's data?
The object can guarantee that its data is always valid, because all changes go through code that checks them.
2. Naming conventions
Python has no private keyword. Instead, it relies on names and on agreement between programmers:
| Name | Meaning | Enforced? |
|---|---|---|
name |
public: part of the class's interface | no limits |
_name |
internal: "do not use from outside" | by convention only |
__name |
name-mangled: harder to reach by accident | by renaming only |
class Private:
def __init__(self):
self.public = 1
self._internal = 2
self.__secret = 3
def reveal(self):
return self.__secret
x = Private()
print(x.public, x._internal, x.reveal())
print(list(vars(x)))
1 2 3
['public', '_internal', '_Private__secret']
Notice the stored name of __secret: _Private__secret. Python renames an attribute that starts with two underscores (and does not end with two), by adding the class name in front. This is called name mangling, and it stops accidents, such as a subclass accidentally using the same name:
x.__secret
AttributeError: 'Private' object has no attribute '__secret'
But it is not real privacy: x._Private__secret still gives 3. The Python saying is "we are all consenting adults": the underscore says "please leave this alone", and you trust the other programmers.
Practical advice:
- Use
_namefor internal attributes and helper methods. It is by far the most common. - Use
__namerarely: only when you really must avoid a clash with a subclass. - Never use double leading and trailing underscores (
__name__) for your own names: those belong to Python (lesson 13.7).
3. A read-only attribute with @property
The @property decorator (lesson 11.11) turns a method into something that looks like an attribute. With only a getter, the value can be read but not set:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, x):
if x <= 0:
raise ValueError("deposit must be positive")
self._balance += x
a = Account("Rina", 100)
print(a.balance)
a.deposit(50)
print(a.balance)
100
150
You write a.balance, with no brackets, but Python calls the method. The money can only change through deposit, which checks the amount:
a.balance = 5
AttributeError: property 'balance' of 'Account' object has no setter
a.deposit(-1)
ValueError: deposit must be positive
(The exact wording of the AttributeError differs between Python versions.) The stored value is in _balance; the public name balance is the property.
4. A setter that validates
To allow changes with checking, add a setter, a method decorated with @name.setter. It runs whenever someone assigns to the attribute:
class Temperature:
def __init__(self, celsius=0):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature(25)
print(t.celsius)
t.celsius = 100
print(t.celsius)
try:
t.celsius = -300
except ValueError as e:
print("ValueError:", e)
print(t.celsius)
25
100
ValueError: below absolute zero
100
Look at the details:
- The property and its setter have the same name,
celsius. The value is stored in_celsius. - In
__init__, the lineself.celsius = celsiusgoes through the setter, so a bad value is rejected even when the object is created. - The failed assignment left the old value in place.
class Positive:
def __init__(self, v):
self.value = v
@property
def value(self):
return self._v
@value.setter
def value(self, v):
if not isinstance(v, (int, float)):
raise TypeError("number required")
if v <= 0:
raise ValueError("must be positive")
self._v = v
for bad in ["x", -1, 0]:
try:
Positive(bad)
except (TypeError, ValueError) as e:
print(type(e).__name__, e)
print(Positive(5).value)
TypeError number required
ValueError must be positive
ValueError must be positive
5
5. Computed properties
A property can calculate its value from other data. It looks like an attribute but is always up to date, and nothing is stored twice:
class Circle:
def __init__(self, r):
self.r = r
@property
def area(self):
return 3.14159 * self.r ** 2
@property
def diameter(self):
return 2 * self.r
c = Circle(2)
print(round(c.area, 2), c.diameter)
c.r = 3
print(round(c.area, 2), c.diameter)
12.57 4
28.27 6
When the radius changed, area and diameter followed automatically. If they had been stored in __init__, they would be stale. A read-only computed property raises the same AttributeError if you try to assign to it.
Two properties can present the same data in two units, with a setter that converts:
class Temperature2(Temperature):
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, f):
self.celsius = (f - 32) * 5 / 9
t = Temperature2(25)
print(t.celsius, t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)
t.fahrenheit = 32
print(t.celsius)
25 77.0
212.0
0.0
The data is stored once, in Celsius. Fahrenheit is a view of it. Setting fahrenheit goes through the Celsius setter, so the same validation applies.
6. A deleter
A third method, @name.deleter, runs on del obj.name. It is rarely needed:
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return f"{self.first} {self.last}"
@full_name.setter
def full_name(self, v):
self.first, self.last = v.split(" ", 1)
@full_name.deleter
def full_name(self):
self.first = self.last = ""
p = Person("Rina", "Hoque")
print(p.full_name)
p.full_name = "Sam Lee"
print(p.first, p.last)
del p.full_name
print(repr(p.first))
Rina Hoque
Sam Lee
''
7. Why properties?
The big advantage: callers use the same simple syntax as for a plain attribute: obj.balance, obj.celsius = 20. So you can start with a plain attribute and add a property later (to validate, compute or log) without changing any code that uses the class.
That is why Python programmers do not write get_balance() and set_balance() methods for everything. Use a plain attribute when no rule is needed; switch to a property when you need one.
| Need | Use |
|---|---|
| nothing special | a plain attribute |
| read-only value | a property with a getter only |
| checking or converting on assignment | a property with a setter |
| a value derived from other data | a computed property |
| an expensive value, calculated once | cached_property (next section) |
8. Cached properties
A property recalculates every time it is read. For an expensive calculation that does not change, functools.cached_property calculates it once, then remembers it on the object:
import functools
class L2:
@functools.cached_property
def big(self):
print("expensive")
return 42
o = L2()
print(o.big)
print(o.big)
expensive
42
42
The word expensive was printed once. After the first use, the value is stored in the object like a normal attribute. Use it only when the answer cannot change (or you are happy to reset it by deleting the attribute).
A manual version of the same idea checks for None:
class Lazy:
def __init__(self):
self._data = None
@property
def data(self):
if self._data is None:
print("computing...")
self._data = sum(range(1000))
return self._data
l = Lazy()
print(l.data, l.data)
computing...
499500 499500
9. Protecting lists and dictionaries
A property that returns a list gives the caller your actual list, which they can change, breaking your rules (lesson 11.9). Return a copy or an immutable version:
class Items:
def __init__(self):
self._items = []
@property
def items(self):
return tuple(self._items)
def add(self, x):
self._items.append(x)
i = Items()
i.add(1)
i.add(2)
print(i.items)
i.items.append(3)
(1, 2)
AttributeError: 'tuple' object has no attribute 'append'
The caller can read the items, but can add them only through add, where you can check them. list(self._items) would also protect the data (it returns a copy that the caller may change harmlessly).
Worked example: a safe bank account
Make an account whose balance can be read but not set directly, rejects bad amounts, keeps a history, and cannot be overdrawn.
class SafeAccount:
def __init__(self, owner, opening=0):
if opening < 0:
raise ValueError("opening balance must not be negative")
self.owner = owner
self._balance = opening
self._history = [("open", opening)]
@property
def balance(self):
return self._balance
@property
def history(self):
return tuple(self._history)
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
self._history.append(("deposit", amount))
return self
def withdraw(self, amount):
if amount <= 0:
raise ValueError("withdrawal must be positive")
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
self._history.append(("withdraw", amount))
return self
acc = SafeAccount("Rina", 100)
acc.deposit(50).withdraw(30)
print(acc.balance)
print(acc.history)
for action in (lambda: acc.withdraw(500), lambda: acc.deposit(-5), lambda: setattr(acc, "balance", 1)):
try:
action()
except (ValueError, AttributeError) as e:
print(type(e).__name__)
print(acc.balance, len(acc.history))
120
(('open', 100), ('deposit', 50), ('withdraw', 30))
ValueError
ValueError
AttributeError
120 3
| Feature | How |
|---|---|
| balance readable, not settable | a getter-only @property |
| a history nobody can edit | a property returning a tuple copy |
| valid amounts only | checks in deposit and withdraw |
| chaining | methods return self |
| failures change nothing | all three bad actions left the balance at 120 and the history at 3 entries |
The owner, amounts and rules are made up.
Common mistakes
- Using the same name for the stored value and the property (
self.balance = ...inside thebalanceproperty), which recurses forever. Store in_balance. - Forgetting
@name.setter(or giving the setter a different name), so the property is read-only. - Returning a mutable internal list from a property.
- Writing
get_xandset_xmethods everywhere instead of a plain attribute or a property. - Setting
self._celsius = valuein__init__and bypassing the validation. Useself.celsius = value. - Relying on
__namefor security. It only prevents accidents.
Key takeaways
- Encapsulation means an object guards its data so that it stays valid.
_namemarks internal data (convention only);__nameis renamed to_Class__nameto avoid accidental clashes; Python has no true privacy.@propertymakes a method read like an attribute: getter only for read-only, plus@name.setterto validate, or compute the value from other data.- Start with plain attributes and add properties only when you need a rule; callers do not have to change.
functools.cached_propertycalculates once; return tuples or copies to protect internal collections.
Practice
1. How do you make balance readable but not assignable from outside?
Show answer
Store the value in _balance and define a getter with @property def balance(self): return self._balance, and no setter.
2. What is wrong with @property def x(self): return self.x?
Show answer
The property calls itself forever (infinite recursion). Store the data under another name, such as _x, and return that.
3. Why does self.celsius = celsius in __init__ (not self._celsius) matter when celsius is a property?
Show answer
It goes through the setter, so the validation runs even when the object is created. Writing self._celsius would skip the check.
4. What does Python do to the name __secret inside class Private?
Show answer
It renames it to _Private__secret (name mangling), which prevents accidental clashes but is not true privacy.
5. A class stores self._items = []. How should a property return it safely?
Show answer
Return a copy or an immutable version, such as tuple(self._items) or list(self._items), so that callers cannot change the internal list.
6. When should you use functools.cached_property?
Show answer
For an expensive value that does not change, so that it is calculated only the first time and remembered.