Skip to content

Properties and Encapsulation

Beginning of the lesson

Properties and Encapsulation

Guard your objects' data with clean attribute syntax and quiet validation

Big Idea: Encapsulation means bundling data together with the code that is allowed to touch it, and controlling how the outside world reads or changes that data. In Python you rarely lock attributes away completely; instead you use naming conventions to signal intent and the @property decorator to run validation the moment an attribute is read or written — all while callers keep writing plain obj.value.
By the end you will be able to:
  • explain what encapsulation is and why it matters,
  • read the _single and __double underscore conventions correctly,
  • turn a method into a read-only attribute with @property,
  • add a @x.setter that 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers