Velamuvi AIAcademy

Lesson 13 of 15 · Design

Encapsulation

Learn encapsulation in Python: hiding an object's internal data behind methods, the single and double underscore conventions, name mangling and why it makes code safer to change.

  • 8 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What encapsulation is and why it matters
  • The difference between public, protected and private names in Python
  • What name mangling does, and what it does not do
  • How methods and properties guard an object's data
  • How encapsulation lets you change code safely later

Hiding the inside, sharing the outside

When you drive a car, you use the steering wheel, pedals and gear stick. You never touch the fuel injectors or the engine timing directly. The car hides its complicated inside and gives you a small, safe set of controls. If the manufacturer redesigns the engine, you can still drive the new model the same way.

Encapsulation has two benefits:

  • Safety. Data can only change through methods that check the rules, so an object cannot end up in a broken state.
  • Freedom to change. The inside can be rewritten later without breaking any code that uses the object, as long as the outside controls stay the same.

The problem without encapsulation

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Not enough money")
        self.balance -= amount


account = BankAccount("Ada", 100)
account.balance = -1000000      # skips every rule in withdraw()
print(account.balance)

The withdraw() method carefully protects the balance, but any code can simply ignore it and change balance directly.

Public, protected and private names

Python does not lock attributes away completely. Instead, it uses naming conventions that every Python programmer understands.

StyleExampleMeaning
Publicaccount.owneruse freely
Protectedaccount._balanceinternal: use the methods instead
Privateaccount.__pininternal, and renamed by Python

Protected attributes with a property

The usual pattern: store the data under a protected name, change it only through methods that check the rules, and offer a read-only property so people can still see the value.

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("Not enough money")
        self._balance -= amount


account = BankAccount("Ada", 100)
account.deposit(50)
account.withdraw(30)
print(account.balance)

try:
    account.balance = -1000000
except AttributeError:
    print("The balance can only change through deposit() and withdraw()")

Now the only ways to change the money are the two methods that check the rules. Reading the balance is still easy.

Private attributes and name mangling

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, pin):
        self.owner = owner
        self.__pin = pin

    def check_pin(self, attempt):
        return attempt == self.__pin


account = BankAccount("Ada", "4821")
print(account.check_pin("0000"))
print(account.check_pin("4821"))

try:
    print(account.__pin)
except AttributeError:
    print("No attribute called __pin from outside")

print(account._BankAccount__pin)

Inside the class, self.__pin works normally. Outside, the name __pin cannot be found. But the last line shows the truth: the data is still there under its renamed form.

The main real use of double underscores is to stop a child class from accidentally overwriting a parent's internal attribute by using the same name. In everyday code, a single underscore is the normal choice.

Freedom to change the inside

Here is encapsulation's biggest win. Suppose you decide the account should remember every transaction, not just the balance. Because outside code only ever used deposit(), withdraw() and balance, you can rewrite the inside completely:

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._history = [balance]       # new design: store every change

    @property
    def balance(self):
        return sum(self._history)       # worked out from the history

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._history.append(amount)

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Not enough money")
        self._history.append(-amount)


# The code that USES the account is exactly the same as before
account = BankAccount("Ada", 100)
account.deposit(50)
account.withdraw(30)
print(account.balance)
print(account._history)

The program using the account did not change at all, and got the same answer. If outside code had been reaching into account._balance directly, this change would have broken it.

Common mistakes

Practice exercise

Build a wallet whose money can only change through methods that check the rules.

Your solutionPython
# Write a class called Wallet that encapsulates its money.
# - __init__ stores the starting amount in a protected attribute self._balance (default 0)
# - balance is a read-only property that returns self._balance
# - add(self, amount) raises ValueError("Amount must be positive") if amount <= 0
# - spend(self, amount) raises ValueError("Not enough money") if amount > balance


wallet = Wallet(500)
wallet.add(200)
wallet.spend(650)
print(wallet.balance)
try:
    wallet.spend(100)
except ValueError as error:
    print(error)
try:
    wallet.add(-5)
except ValueError as error:
    print(error)
try:
    wallet.balance = 999
except AttributeError:
    print("Read-only")

# Output must be exactly:
# 50
# Not enough money
# Amount must be positive
# Read-only
Knowledge check

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

Summary

  • Encapsulation hides an object's inside and exposes a small set of safe controls.
  • Public names are for everyone. A single underscore marks a protected internal name. Two underscores make a private name that Python renames (name mangling).
  • Underscores prevent accidents, not attacks. They are not a security feature.
  • The common pattern is a protected attribute, methods that check the rules, and a read-only property.
  • Encapsulation lets you rewrite a class's inside without breaking the code that uses it.

Next: classes that are never used directly, but set the rules for their children.

Finished reading? Tick it off to track your progress.