▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Encapsulation and properties
Protect an object's data with @property.
🎬 Video version coming soon — read it now
Encapsulation means an object protects its own data, so it can't be put into an invalid state. A bank balance shouldn't be set to minus a lakh just because someone typed acc.balance = -100000.
Python's convention: a leading underscore
Python doesn't strictly block access to _balance. The underscore is a convention that means "internal detail, use the methods instead". Python developers respect it. (A double underscore, __balance, makes the name harder to reach by accident, but it is rarely needed.)
@property: read like an attribute, controlled like a method
The balance can be read easily but can only change through deposit and withdraw, which check the rules.
A setter that validates
Users of the class still write the simple s.cgpa = 9.0, but bad values are rejected.
Computed properties
r.area is always up to date because it's calculated each time it's read.
In one line
Mark internal data with an underscore and use @property to expose it safely, validating any changes in a setter.
Share with a friend