Properties and Encapsulation
Guard your objects' data with clean attribute syntax and quiet validation
@property decorator to run validation the moment an attribute is read or written — all while callers keep writing plain obj.value.
- explain what encapsulation is and why it matters,
- read the
_singleand__doubleunderscore conventions correctly, - turn a method into a read-only attribute with
@property, - add a
@x.setterthat validates every write, - build computed (derived) properties, and know the trade-offs.
1. What is encapsulation?
Encapsulation is one of the pillars of object-oriented programming. It is the discipline of keeping an object's internal state private and exposing a controlled, well-defined surface for the rest of the program to use. The object becomes responsible for its own data: it decides what a valid value is, and no outsider can quietly put it into a broken state.
Think of an ATM. You never reach into the machine to move cash between drawers. You interact through a small, guarded interface — insert a card, enter a PIN, request an amount — and the machine enforces the rules (correct PIN, sufficient balance, daily limit) before it touches the money inside. The cash trays are the private state; the keypad and screen are the public interface. Encapsulation is designing your classes the same way.
Without it, any part of a large program can reach in and set account.balance = -9999, and now you have a bug that could have been born anywhere. With encapsulation, the class itself refuses invalid values, so the bug is caught at the source.