Skip to content
IT Vizag
← Objects & Classes

▶ 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

Lesson 6 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

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

🔒 Code example: sign up free (above) to unlock it.

The balance can be read easily but can only change through deposit and withdraw, which check the rules.

A setter that validates

🔒 Code example: sign up free (above) to unlock it.

Users of the class still write the simple s.cgpa = 9.0, but bad values are rejected.

Computed properties

🔒 Code example: sign up free (above) to unlock it.

r.area is always up to date because it's calculated each time it's read.

Tip: Start with plain attributes. Switch to @property only when you need validation or a computed value; the code that uses your class doesn't have to change.

In one line

Mark internal data with an underscore and use @property to expose it safely, validating any changes in a setter.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend