Lesson 6 of 7 · Classes and Objects · 3 min read · Updated

Encapsulation and properties

Marking what is internal, and guarding attributes with properties.

Encapsulation means an object looks after its own data: outside code goes through methods that keep the rules, rather than changing values directly. Python relies on convention for this more than on locks.

  • name — public: use it freely.
  • _name — one underscore: internal. Outside code can touch it but should not.
  • __name — two underscores: Python renames it to _ClassName__name, so a child class cannot clash with it by accident.
python
class Secret:
    def __init__(self):
        self.__pin = 1234

s = Secret()
print(hasattr(s, "__pin"), hasattr(s, "_Secret__pin"))
Output
False True

Properties

python
class Account:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("balance cannot be negative")
        self._balance = value

acc = Account(500)
print(acc.balance)
acc.balance = 800
print(acc.balance)
try:
    acc.balance = -50
except ValueError as e:
    print("Refused:", e)
Output
500
800
Refused: balance cannot be negative

A property looks like a plain attribute from outside — acc.balance, no brackets — but runs a method underneath. Reading it calls the @property method; assigning calls the .setter, which can check the value. Leave out the setter and the attribute becomes read-only.

Note

The @ lines are decorators, explained in the Advanced topic. You can use @property now without knowing how it works inside.

What does a single leading underscore, as in self._total, mean?

Try this now

  1. Give a Student class a marks property that refuses values outside 0 to 100.
  2. Add a read-only grade property that works out A, B or C from the marks.

Create a free account to save your progress, or sign in.