L2 · Working engineerObject-oriented Python~5 min · 3 tests#74

Encapsulation: Private Balance + @property

Protect an account balance with a private attribute and a read-only @property so it can only change through deposit(). Python encapsulation, tested.

The problem

Implement Account:

  • deposit(amount) adds a positive amount (raise ValueError otherwise)
  • balance is a read-only property — reading works, assigning account.balance = 5 raises AttributeError
  • store the value in a "private" attribute (self._balance or self.__balance)

Examples

  1. Example 1

    Input

    (lambda a: (a.deposit(1000), a.balance)[1])(Account())

    Expected output

    1000
  2. Example 2

    Input

    try_overwrite(Account)

    Expected output

    ('blocked', 1000)

+ 1 hidden test on Submit.

Edge cases to ask about

  • Assignment blocked
  • Invalid deposit
How the tests call your code

These helpers run before your code. The test inputs above call them.

def try_overwrite(cls):
    acc = cls()
    acc.deposit(1000)
    try:
        acc.balance = 5
        return ("assigned", acc.balance)
    except AttributeError:
        return ("blocked", acc.balance)

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · Account
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Name-mangled attribute + @propertyO(1)O(1)Python has no true private; __x is mangled to _Class__x.
    Walkthrough of the optimal approach (try it yourself first)

    Python has no truly private attributes. A single underscore (_balance) is a convention; a double underscore (__balance) is name-mangled to _Account__balance, which prevents accidental clashes in subclasses.

    @property without a setter exposes the value as read-only: reading works, assignment raises AttributeError. All changes go through deposit, which enforces the rules.

    Complexity: O(1) time, O(1) space. Constant-time attribute access.

    Reveal the reference solution
    class Account:
        def __init__(self):
            self.__balance = 0
    
        @property
        def balance(self):
            return self.__balance
    
        def deposit(self, amount):
            if amount <= 0:
                raise ValueError("deposit must be positive")
            self.__balance += amount

    Follow-ups interviewers ask

    • Add a validated setter with @balance.setter.
    • How would you still reach _Account__balance?

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Encapsulation: Private Balance + @property in Python?

    The optimal solution runs in O(1) time and O(1) auxiliary space. Constant-time attribute access.

    What follow-up questions do interviewers ask about Encapsulation: Private Balance + @property?

    Add a validated setter with @balance.setter. How would you still reach _Account__balance?