PY-101 ยท Object-oriented Python
Encapsulation
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
Encapsulation means an object protects its own data and only lets the outside change it in controlled ways. Python marks internal attributes with a leading underscore, such as self._balance, and @property lets you expose a value that reads like an attribute but runs checks behind the scenes. That way nobody can set a balance to -500 by accident.
- Mark internal data with _
- Use @property and a setter
- Validate values on the way in
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
class Thermostat:def __init__(self, temp):self._temp = temp@propertydef temp(self):return self._temp@temp.setterdef temp(self, value):if not 10 <= value <= 30:raise ValueError("temperature must be 10-30")self._temp = valuet = Thermostat(22)t.temp = 25print(t.temp)try:t.temp = 99except ValueError as e:print("Rejected:", e)print(t.temp)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
25
Rejected: temperature must be 10-30
25 ๐ฏ Give Person a name property whose setter rejects empty names with ValueError. Person("Asha").name prints Asha; setting it to "" must raise ValueError.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
Store self._name; add @property name and @name.setter that raises ValueError if not value.strip().
- The problemAny line of code anywhere can write account.balance = -500. One bad line and the bank is wrong. Encapsulation forces every change through a door that checks the rules.
- The Python idea
class Name:Encapsulation means an object protects its own data and only lets the outside change it in controlled ways. - In real lifeLibraries keep their internals in _underscore attributes, so they can change them freely between versions without breaking your code.
Start with a question
Any line of code anywhere can write account.balance = -500. One bad line and the bank is wrong. Encapsulation forces every change through a door that checks the rules.
Bugs where data is changed from somewhere unexpected are the hardest to find. Encapsulation keeps changes in one place.
Explain it like I'm 10
It is a piggy bank with a slot: anyone can put coins in through the slot, but you cannot reach in and grab them.
The technical explanation
self._balance means "internal, use the methods". It is a convention every Python developer recognises.
@property def balance(self): lets callers write acc.balance (no brackets) to read it.
@balance.setter runs when someone writes acc.balance = x, so you can reject bad values.
Syntax
class Name:
@property
def value(self):
return self._value
@value.setter
def value(self, v):
...
self._value = v Real-world scenario
Libraries keep their internals in _underscore attributes, so they can change them freely between versions without breaking your code.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Dunder methods โQuestions people ask
Does Python have private variables?
Not truly. A single underscore means internal by convention. A double underscore (__x) triggers name mangling, which makes accidental access harder but not impossible.
When should I use @property?
When reading or setting a value needs logic (validation, conversion, or computing it from other data) but you want callers to use simple attribute syntax.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Does Python have private variables?
Not truly. A single underscore means internal by convention. A double underscore (__x) triggers name mangling, which makes accidental access harder but not impossible.
beginner When should I use @property?
When reading or setting a value needs logic (validation, conversion, or computing it from other data) but you want callers to use simple attribute syntax.
intermediate What does a leading underscore like _balance mean?
Internal: please use the methods. A convention for internal data.
intermediate What does @property let you do?
Call a method without brackets, like an attribute. obj.value runs the getter.
Quick revision
Remember
- Mark internal data with _
- Use @property and a setter
- Validate values on the way in
- Python does not truly lock attributes; the underscore is a polite "please do not touch". Respect it, and add @property when rules matter.
Syntax
class Name:
@property
def value(self):
return self._value
@value.setter
def value(self, v):
...
self._value = v Official documentation
- property() (docs.python.org)