Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in Python: Encapsulation with a Class

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Python has no private keyword. By convention, store the balance in an attribute that starts with an underscore, self._balance, to tell other code "hands off".

What the class must have (Python):

  • __init__(self, initial_balance): creates an account that starts with the given balance.
  • deposit(self, amount): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • withdraw(self, amount): if amount is zero or negative, or larger than the balance, change nothing and return False. Otherwise subtract it from the balance and return True. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • get_balance(self): returns the current balance. It is the only way for outside code to read it.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
account.withdraw(200)
print("Balance: " + str(int(account.get_balance())))
account.deposit(-20)
account.deposit(0)
account.withdraw(-5)
print("Balance: " + str(int(account.get_balance())))
if account.withdraw(120):
    print("Withdrew all")
print("Balance: " + str(int(account.get_balance())))
if not account.withdraw(1):
    print("Rejected")

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

In __init__, write self._balance = initial_balance. Methods read and change it as self._balance.

if amount <= 0 or amount > self._balance: return False, then self._balance -= amount and return True.

class BankAccount:
    def __init__(self, initial_balance):
        self._balance = initial_balance

    def deposit(self, amount):
        if amount <= 0: return
        self._balance += amount

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance: return False
        self._balance -= amount
        return True

    def get_balance(self):
        return self._balance

account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
account.withdraw(200)
print("Balance: " + str(int(account.get_balance())))
account.deposit(-20)
account.deposit(0)
account.withdraw(-5)
print("Balance: " + str(int(account.get_balance())))
if account.withdraw(120):
    print("Withdrew all")
print("Balance: " + str(int(account.get_balance())))
if not account.withdraw(1):
    print("Rejected")

STEP 1 OF 12
    Ctrl + Enter to check

    PYTHON · PROJECTS: OBJECT-ORIENTED

    Bank Account in Python, explained

    Problem overview

    You build a BankAccount class that guards its own balance. Outside code never changes the money directly. It asks the object through methods, and the methods check the rules first. Keeping data behind methods that enforce rules is called encapsulation.

    The class has four members:

    • __init__(self, initial_balance) creates an account with a starting balance.
    • deposit(self, amount) adds money. A zero or negative amount is ignored: no error, and the balance stays as it was.
    • withdraw(self, amount) removes money and returns True. It returns False and changes nothing when the amount is zero, negative or larger than the balance. Withdrawing exactly the whole balance is allowed.
    • get_balance(self) returns the balance.

    The driver starts with 100, deposits 50, withdraws 30 and then tries to withdraw 200. It prints the balance, tries three invalid operations, prints again, empties the account and finally asks for one more unit.

    Approach: a private attribute and guard clauses

    Python has no private keyword. The convention is to start the attribute name with an underscore: self._balance tells other programmers that it is internal and that they should use the methods. Python doesn't enforce this. Code that writes account._balance = 1000000 succeeds and get_balance() then returns 1000000. The underscore is a promise between programmers, and the methods are the intended door.

    Both deposit and withdraw use a guard clause: the first line rejects bad input and leaves the method, so the rest of the body only sees valid amounts. The two methods differ in how they say no. deposit just returns, which gives None. withdraw must tell the caller what happened, so it returns False on refusal and True on success, and the driver uses that answer in its if statements.

    Step by step

    1. Declare the class BankAccount. All the account's state and rules live inside it.
    2. Start the constructor, __init__(self, initial_balance). Python calls it once when you write BankAccount(100), and self is the new account.
    3. Store the starting balance in self._balance. With self. the value outlives the constructor, so the other methods can use it.
    4. Start deposit(self, amount). It changes the balance and answers nothing.
    5. Add the guard: if amount <= 0: return, written on one line. A deposit of zero or less is ignored.
    6. Add the amount to self._balance. Only positive amounts get this far.
    7. Start withdraw(self, amount), which will answer True or False.
    8. Refuse bad requests with one guard: amount <= 0 or amount > self._balance returns False. The comparison is >, not >=, so asking for exactly the balance passes.
    9. Subtract the amount from the balance.
    10. Return True: reaching this line means the money left the account.
    11. Start get_balance(self), a getter that lets outside code read the balance without a reason to touch it.
    12. Return self._balance from it.

    The solution in Python

    class BankAccount:
        def __init__(self, initial_balance):
            self._balance = initial_balance
    
        def deposit(self, amount):
            if amount <= 0: return
            self._balance += amount
    
        def withdraw(self, amount):
            if amount <= 0 or amount > self._balance: return False
            self._balance -= amount
            return True
    
        def get_balance(self):
            return self._balance
    
    account = BankAccount(100)
    account.deposit(50)
    account.withdraw(30)
    account.withdraw(200)
    print("Balance: " + str(int(account.get_balance())))
    account.deposit(-20)
    account.deposit(0)
    account.withdraw(-5)
    print("Balance: " + str(int(account.get_balance())))
    if account.withdraw(120):
        print("Withdrew all")
    print("Balance: " + str(int(account.get_balance())))
    if not account.withdraw(1):
        print("Rejected")
    

    The class ends after get_balance. Everything below it is the driver that uses the class.

    Python details worth a look

    • One-line guards. if amount <= 0: return is legal when the body is a single statement. In deposit the bare return ends the method and gives back None.
    • or short-circuits. In amount <= 0 or amount > self._balance, the second test only runs when the first is false. Both parts are plain comparisons, so the order doesn't change the result here.
    • self is explicit. Every method lists self first, and every attribute is read as self._balance. A bare _balance would be a different name that doesn't exist.
    • int(...) in the driver. The driver prints str(int(account.get_balance())). With whole numbers the int changes nothing. Your class doesn't convert: with deposit(0.5) on an empty account, get_balance() returns 0.5.

    What the driver prints

    Balance: 120
    Balance: 120
    Withdrew all
    Balance: 0
    Rejected
    

    100 plus 50 minus 30 is 120, and the refused withdrawal of 200 leaves it there. The deposits of -20 and 0 and the withdrawal of -5 are all ignored, so the balance is still 120. Withdrawing 120 succeeds and empties the account, and withdrawing 1 more is rejected.

    Edge cases and common mistakes

    • The whole balance. BankAccount(100).withdraw(100) returns True and leaves 0. Writing amount >= self._balance in the guard would wrongly refuse it.
    • Overdrawing. After that, withdraw(1) returns False and the balance stays 0. On an account with 50, withdraw(51) returns False and the balance is still 50.
    • A zero amount. withdraw(0) returns False, even on an empty account, because the amount is not positive.
    • Forgetting the return value. Without return True at the end, a successful withdrawal returns None. The driver's if account.withdraw(120) would then be false and Withdrew all would never print.
    • Changing the balance before checking. Subtracting first and validating afterwards leaves the account changed on a refusal. Put the guard first.
    • Skipping self.. Writing _balance = initial_balance in the constructor creates a local variable that disappears when the constructor ends.

    Key takeaways

    • A leading underscore marks an attribute as internal. It is a convention, and the methods are the intended way in.
    • Guard clauses at the top of a method keep the invalid cases out of the main logic.
    • A method that can refuse should say so through its return value.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free