Python Tutorial: Encapsulation
Hide the internals. Control access with properties, getters, setters, and private attributes.
Keep internals private
Should users of your class be able to set `balance = -10000` directly? Or `age = -5`?
Encapsulation lets you control how class data is accessed and modified. You decide what is public, what is private, and what the rules are. Ten steps.
What you'll learn in this Python encapsulation tutorial
This interactive Python tutorial has 6 hands-on exercises. Estimated time: 18 minutes.
- The problem with public everything — Right now, anyone can set `account.balance = -9999`. No error, no warning — just broken data.
- _ convention — 'please don't touch this' — Python's first line of encapsulation: prefix an attribute with `_` to signal it's private.
- @property — read access without () — `@property` turns a method into an attribute that you access *without calling it*:
- @setter — controlled write access — Now add a setter — a method that runs when someone assigns to `balance`. The setter validates before storing.
- Read-only property — A property without a setter is read-only. Trying to assign to it raises `AttributeError`.
- Build a validated User — Final challenge — no starter code.
Python Encapsulation concepts covered
- Keep internals private