← Python from Scratch Lesson 71 of 78 · 10 XP

Encapsulation

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Encapsulation means hiding an object's inner workings and letting others work with it only through well-thought-out methods. That way nobody can accidentally break the data — for example, put a negative balance into an account.

Python has no "locks" like Java or C++; it has conventions:

  • _balance — "internal, don't touch from outside" (one underscore);
  • __balance — Python renames the attribute to _BankAccount__balance, and you can't simply reach it from outside.

To let outside code read a value but not change it, use @property:

class BankAccount:
    def __init__(self):
        self.__balance = 0

    @property
    def balance(self):          # read like an attribute: acc.balance
        return self.__balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("The amount must be positive")
        self.__balance += amount
acc = BankAccount()
acc.deposit(100)
acc.balance          # 100
acc.balance = 999    # AttributeError: it can't be changed directly

Task. Create a BankAccount with a private balance, a read-only balance property, and the methods deposit(amount) and withdraw(amount). If there isn't enough money in the account, withdraw raises a ValueError. deposit doesn't accept a non-positive amount either.

The checks use raises(function, Error) — a helper from the platform: it calls the function and answers True if it raised the expected error.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.