Lesson · Object-Oriented Python
Encapsulation & Properties
55 min readEncapsulation & Properties
Python favors convention and properties over rigid access modifiers. A property can preserve a simple attribute interface while adding validation, calculation, or compatibility logic.
Learning goals
- Explain how
self.balance = balancein__init__runs the setter even though it looks like plain attribute assignment. - Trace
account.balancefrom attribute syntax through the@propertygetter toself._balance. - Describe what the underscore in
_balancecommunicates and what Python actually enforces at runtime. - Predict what
Account(-5)raises and which line of the class performs the check. - Choose between a plain public attribute, a single-underscore name, and a property for a given piece of state.
Mental model
The property turns attribute syntax into a method call in both directions, which is why the class can validate without changing how callers read or write balance. The underscore on _balance is the second half of the story: it marks the storage as internal by convention, and nothing in the language stops a determined caller from touching it.
Mental model
read it top to bottom
account.balance = 150 ↓ assignment syntax finds a data descriptor on the class @balance.setter runs → validates → writes self._balance ↓ account.balance (read) ↓ @property getter runs → returns self._balance
Core idea
Encapsulation in Python is a social contract rather than a lock: a leading underscore tells other readers and tools that a name is internal, while a property lets the class keep a plain-looking attribute interface and still run code on every read or write. The payoff is that account.balance = -1 can raise ValueError today, and cached or computed storage could replace _balance tomorrow without touching a single caller. Prefer the lightest mechanism: a public attribute until the class has a rule to enforce.
Convention-based encapsulation
Convention-based encapsulation marks internal names with a single leading underscore and relies on readers and tools to respect the marker; Python performs no access check at runtime. _balance is a normal attribute that any code can read or write, so the convention protects intent rather than data. Use it to signal that the class owns the name and callers should go through its public interface.
Public names
A public name is an attribute or method with no leading underscore that the class commits to supporting; balance is public, while _balance is not. Keep the public surface small enough that each name has a clear contract, because every public name becomes something you can no longer freely rename. The property keeps that surface stable while the storage behind it can change.
_protected_by_convention
_protected_by_convention is the naming convention for internal state: one leading underscore tells other programmers that the name belongs to the class's implementation. Python still lets any caller read or write it, so the marker is a contract, not a lock, and tooling uses it to adjust autocomplete and documentation. Reach for it when a name must exist but is not part of the promised interface.
Name mangling
Name mangling applies to identifiers with two leading underscores inside a class body: __balance becomes _Account__balance in the attribute namespace. It exists to avoid collisions with names in subclasses, not to prevent access, since anyone who knows the transformed name can still use it. Use it for attributes that a subclass should not accidentally shadow.
property
A property runs methods behind normal attribute syntax. It can add validation or computed behavior while preserving a simple public interface.
Pythonic getters/setters
Pythonic getters and setters use @property and @<name>.setter so the class keeps the plain account.balance interface while running validation or computation on each access. The point is that replacing a public attribute with a property later is a source-compatible change, so you do not need get_balance() ceremony up front. Write them when the class has a rule to enforce or a value to compute, not by reflex.
Validation
Constructor validation prevents creation of objects that violate essential invariants. Raise a precise exception close to the invalid input rather than letting a corrupted object escape.
Walkthrough
account = Account(100)calls__init__, whereself.balance = balancelooks like a plain assignment but is routed to the@balance.setter, because the class definesbalanceas a property.- The setter checks
if value < 0: raise ValueError("negative balance")before the write, then stores intoself._balance, so the validating path is the only public path to the data. print(account.balance)triggers the@propertygetter, which returnsself._balance; the caller keeps attribute syntax and never calls a method.- Predict before running: the printed value, what
Account(-5)raises, and whataccount._balancewould show if you read the underscored name directly.
Experiments to try
- Construct
Account(-5)and read the traceback, then move the validation into a plainset_balancemethod and explain what every caller would have to change. - Set
account.balance = -1on a valid account and confirm the object keeps its previous value because the setter raises before the write. - Read
account._balancedirectly and note that Python allows it; then state what the team convention buys when the language enforces nothing. - Add a
withdraw(self, amount)method that assignsself.balance = self.balance - amountand observe the setter running on that internal assignment too.
Common mistakes
- Forgetting that
self.balance = valueinside the class still goes through the setter: construction can raise from a validation rule, and the assignment can never bypass it. - Writing the setter so it assigns to its own property name, as in
self.balance = valueinsidebalance, which invokes the setter again and recurses untilRecursionError. - Repeating the validation rule in both
__init__and the setter:__init__already runs the setter, so a second check duplicates the rule and the two copies can drift apart. - Treating
_balanceas truly private: any caller can still read and write it, and name mangling with two underscores only renames the attribute, so neither form enforces access.
Practice: Easy
- Run the worked example and print
account._balancenext toaccount.balance; explain why both show100and which name the class treats as public. - Construct
Account(-5)and record the exactValueError; then setaccount.balance = -1on a valid account and confirm the balance is unchanged after the exception. - Delete the setter and keep only the
@propertygetter, then runAccount(100)and explain theAttributeErrorthat comes from assigning to a getter-only property.
Practice: Medium
- Add a
@balance.deleterthat resets the balance to 0, and testdel account.balance; list which public operations the property now supports. - Extend the setter so
account.balance = "100"converts withint(value)before validating; decide whether accepting strings belongs in the setter or at the call site, and test both"100"and"abc". - Rewrite the property pair as explicit
get_balance()andset_balance()methods and list every call site whose syntax changes; argue from the lesson why the property version is the cleaner interface.
Practice: Hard
- Design an
Intervalclass whosestartandendare properties with the invariantstart <= end, enforced on both assignments. Write the tests first, including the order-dependent case where raisingstartaboveendmust fail. - Build a failure lab around two traps: a setter that assigns to its own property name, and an
__init__that readsself._balancebefore any write. Show the exact error, name the mechanism, then fix each. - Connect this lesson to the inheritance lesson: give
Accounta subclass that redefines thebalanceproperty with an extra fee rule, then check whether constructing the subclass still runs the new setter through__init__and explain why.
Lesson checklist
- I can trace
self.balance = balancein__init__into the setter without assuming it is a plain assignment. - I can explain what the underscore in
_balancesignals and what Python enforces. - I can say why read-only, write-only, and computed properties are all still attribute syntax.
- I can name the mechanism that turns
self.balance = valueinside a setter into infinite recursion.
Remember
Encapsulation here is convention plus interface: a single underscore marks internal storage, and a property keeps `account.balance` looking like a plain attribute while the class validates or computes on every read and write. The setter is the only public path to `_balance`, so the invariant holds no matter how callers assign, and the storage behind the property can change later without breaking them.
Interview angles
What is the main purpose of **Convention-based encapsulation**?+
Convention-based encapsulation marks internal names with a single leading underscore and relies on readers and tools to respect the marker; Python performs no access check at runtime. _balance is a normal attribute that any code can read or write, so the convention protects intent rather than data. Use it to signal that the class owns the name and callers should go through its public interface.
What should you pay attention to when using **Public names**?+
A public name is an attribute or method with no leading underscore that the class commits to supporting; balance is public, while _balance is not. Keep the public surface small enough that each name has a clear contract, because every public name becomes something you can no longer freely rename. The property keeps that surface stable while the storage behind it can change.
How does **_protected_by_convention** fit into this lesson?+
_protected_by_convention is the naming convention for internal state: one leading underscore tells other programmers that the name belongs to the class's implementation. Python still lets any caller read or write it, so the marker is a contract, not a lock, and tooling uses it to adjust autocomplete and documentation. Reach for it when a name must exist but is not part of the promised interface.
Why does a setter that runs `self.balance = value` fail, and what should it write instead?+
Assigning to the property name inside its own setter invokes the setter again, so the call recurses until Python raises RecursionError. The setter should write the backing attribute, self._balance = value, after validation.