Underscores, mangling and a read-only property
Try assigning acct.balance = 500 yourself and read the message. Python never stops you from reading acct._balance.
Encapsulation means keeping an object's inner data behind a controlled front door. Python uses naming conventions (_name, __name) instead of locks, and @property lets you turn an attribute into a checked or computed value without changing how callers use it.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Circle with a radius property that rejects negative values with ValueError, and a read-only computed property area (use 3.14 for pi).
Write a class Person with a read-only property full_name built from first and last. Show that assigning to full_name fails.
Write a class Wallet that keeps _coins internal, exposes a read-only coins property, and has spend(n) that refuses to go below zero by raising ValueError.
Explain it without notes
What does encapsulation mean, and how does Python do it without private fields?
What does a leading underscore mean, and how is it different from a double underscore?
What is a property and when would you use one?
Why assign to self.celsius rather than self._celsius in __init__ when celsius has a validating setter?
Expected output
100
Asha: 100
['_Account__pin', '_balance', 'owner']
AttributeError: property 'balance' of 'Account' object has no setter
100
0000
AttributeError: 'Account' object has no attribute '__pin'