🎓 A1Learner
🔍

Python Encapsulation

Encapsulation is guarding data inside a class with its methods. A value such as _balance changes only through those methods.

A protected-feeling balance

The underscore at the start is a gentle warning sign. It marks _balance as internal.

class Wallet:
    def __init__(self):
        self._balance = 0

wallet = Wallet()
print(wallet._balance)

Add money with a method

Other code asks the wallet to add money. The method changes _balance for it.

class Wallet:
    def __init__(self):
        self._balance = 0

    def deposit(self, amount):
        self._balance += amount

wallet = Wallet()
wallet.deposit(50)
print(wallet._balance)

Guard the spending

spend() checks the balance before it pays. The wallet never drops below zero here.

class Wallet:
    def __init__(self):
        self._balance = 20

    def spend(self, amount):
        if amount <= self._balance:
            self._balance -= amount
            print("Paid")
        else:
            print("Not enough money")

wallet = Wallet()
wallet.spend(50)
print(wallet._balance)

Python still trusts you

You can still touch _balance from outside. Python asks you not to, but it will not stop you.

class Wallet:
    def __init__(self):
        self._balance = 10

wallet = Wallet()
wallet._balance = 99
print(wallet._balance)

Example

class Wallet:
    def __init__(self, owner):
        self.owner = owner
        self._balance = 0

    def deposit(self, amount):
        self._balance += amount
        print(f"Deposited {amount}")

    def spend(self, amount):
        if amount <= self._balance:
            self._balance -= amount
            print(f"Spent {amount}")
        else:
            print("Not enough money")

    def show_balance(self):
        print(f"{self.owner} has {self._balance}")

wallet = Wallet("Ava")
wallet.deposit(100)
wallet.spend(30)
wallet.spend(90)
wallet.show_balance()

Key points

  • Encapsulation: keep data inside a class and guard it with methods
  • Use a leading underscore, like _balance, to mark a value as internal
  • Internal: meant for use inside the class, not outside it
  • Use methods like deposit() and spend() to change guarded data safely
  • Python has no true private attribute at this level

In this example, Wallet stores the owner in __init__. It also starts _balance at 0. deposit(100) adds money through a method. spend(30) pays because 30 is not more than the balance. spend(90) asks for too much, so nothing is paid. show_balance() then reports that Ava still has 70. Note: The advanced course covers properties and name mangling. They give you stronger tools later.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does the name _balance tell other programmers?