Tools
Log in
English

Learn to codePython

Python encapsulation

Based on Python 3.12

Hide a bank balance with __name and @property, after seeing the bug it prevents.

In one line

Keep an object's data behind underscore names and let only methods with checks change it. When outside code only needs to read a value, use @property.

Why you need it

If any line can run acc.balance -= 3500, as in the buggy code below, money leaves even when the balance is too low. Adding checks does not help much when balance-changing lines are scattered everywhere and one of them is forgotten.

Hide the balance as __balance and change it only in deposit and withdraw, and the checks and the log live in one place. A new withdrawal rule means editing one method.

Everyday picture

Think of a self-checkout machine. Shoppers never open the cash box; they tap Pay on the screen, and the machine checks the amount. The cash box is the hidden value, the screen buttons are the methods.

The bug you get without encapsulation

class Account:    def __init__(self, owner, balance):        self.owner = owner        self.balance = balance  acc = Account("Jisoo", 2000)acc.balance -= 3500acc.balance += -400print(acc.owner, acc.balance)

When you run it

Jisoo -1900

Any line can change balance, so 3500 leaves an account that held 2000. Nothing checks whether there is enough money.

Adding -400 also goes through, and the balance ends at -1900. With lines like these in ten different files, finding the culprit is slow work.

Example code

main.py · 47 lines
class Account:    def __init__(self, owner, start=0):        if start < 0:            raise ValueError("start must be 0 or more")        self._owner = owner        self.__balance = start        self._log = []     @property    def owner(self):        return self._owner     @property    def balance(self):        return self.__balance     def deposit(self, amount):        if amount <= 0:            print(f"Refused: deposit {amount}")            return False        self.__balance += amount        self._log.append(f"+{amount}")        return True     def withdraw(self, amount):        if amount <= 0 or amount > self.__balance:            print(f"Refused: withdraw {amount}")            return False        self.__balance -= amount        self._log.append(f"-{amount}")        return True     def history(self):        return list(self._log)  acc = Account("Jisoo", 2000)acc.deposit(800)acc.withdraw(5000)acc.deposit(-400)acc.withdraw(1300)try:    acc.balance = 99999except AttributeError as e:    print("Blocked:", e)print(f"{acc.owner}: {acc.balance}")print("History:", acc.history())

When to use it

  • Attributes that must never hold a wrong value (balance, stock, score, age)
  • Changes that must trigger something else (a log entry, a notice, a recalculation)
  • Lists or dicts you show to outside code. Return a copy.

Python has no keyword that locks a value the way private does in Java. _name means "internal, please do not touch", and __name renames the attribute so subclasses do not overwrite it by accident.

The read-only error text "has no setter" appears from Python 3.11. Older versions say "can't set attribute".

Common mistakes

Believing __name can never be changed

__balance is only renamed to _Account__balance; it is not locked. Anyone who knows the new name can still write it. Hiding in Python is an agreement, and using the methods you provided is what keeps the data safe.

Wrong

acc = Account("Jisoo", 2000)acc._Account__balance = -1print(acc.balance)

When you run it-1

Fixed

acc = Account("Jisoo", 2000)acc.withdraw(2001)print(acc.balance)

When you run itRefused: withdraw 2001 2000

Giving the property and the stored value the same name

self.balance = start tries to write the property balance, which has no setter. Store the value under another name such as _balance and let the property read it.

Wrong

class Account:    def __init__(self, start):        self.balance = start     @property    def balance(self):        return self.balance  Account(100)

When you run itAttributeError: property 'balance' of 'Account' object has no setter

Fixed

class Account:    def __init__(self, start):        self._balance = start     @property    def balance(self):        return self._balance  print(Account(100).balance)

When you run it100

Adding a setter with no checks

A setter that stores whatever it receives is no better than a plain attribute. If you add one, reject bad values inside it.

Wrong

class Account:    def __init__(self):        self._balance = 0     @property    def balance(self):        return self._balance     @balance.setter    def balance(self, value):        self._balance = value  acc = Account()acc.balance = -999print(acc.balance)

When you run it-999

Fixed

class Account:    def __init__(self):        self._balance = 0     @property    def balance(self):        return self._balance     @balance.setter    def balance(self, value):        if value < 0:            raise ValueError("balance cannot be negative")        self._balance = value  acc = Account()try:    acc.balance = -999except ValueError as e:    print(e)print(acc.balance)

When you run itbalance cannot be negative 0

Check yourself

Question 1

With the example Account, what happens on acc.balance = 0?

Show the answer

Answer: 2. It raises `AttributeError` balance is a @property that only allows reading. There is no setter, so assigning raises AttributeError.

Question 2

Does vars(acc) contain the key _Account__balance?

acc = Account("Joon", 500)print("_Account__balance" in vars(acc))

Show the answer

Answer: 1. True self.__balance, written inside the class, is stored as _Account__balance. So yes, the key is there.

Questions people ask

Does Python have private?

There is no keyword. _name is an agreement that it is internal, and __name is renamed to _Class__name, which still does not lock it from outside.

When should I use @property?

When outside code should only read a value, or when reading or writing needs a check or a calculation. Callers read it like an attribute, without parentheses.

Should I write getters and setters for everything?

No. Python code usually starts with plain attributes and switches to @property when a check is needed. Calling code does not change.