TExcelTAD
Home › Python › Python Encapsulation

Python Encapsulation

Encapsulation means bundling data with the methods that work on it, and controlling how the outside world can touch that data. The goal is to protect an object's internal state from being put into an invalid condition — a bank balance should never be changed without going through deposit() or withdraw().

Many languages enforce this with private keywords. Python takes a gentler approach: "we're all consenting adults here". It uses naming conventions and properties.

Public, protected and private names

Name Convention Meaning
balance public part of the official interface, use freely
_balance "protected" internal detail — please don't touch from outside
__balance "private" name-mangled to avoid accidental clashes in subclasses
python · try it yourself
class Account:
    def __init__(self, owner, balance):
        self.owner = owner          # public
        self._history = []          # internal
        self.__pin = "1234"         # name-mangled

    def check_pin(self, pin):
        return pin == self.__pin

a = Account("Duy", 100)
print(a.owner)
print(a._history)                   # works, but you were warned
print(a.check_pin("0000"))

try:
    print(a.__pin)
except AttributeError as err:
    print("AttributeError:", err)

print(a._Account__pin)              # the mangled name - don't do this!
Duy
[]
False
AttributeError: 'Account' object has no attribute '__pin'
1234

Python renamed __pin to _Account__pin behind the scenes. It is hidden from casual access, not truly secret. The real purpose of double underscores is to stop subclasses from accidentally overwriting an attribute with the same name.

Getters and setters with @property

Suppose a Product has a price that must never be negative. In Python you don't write get_price()/set_price() methods up front. Start with a plain attribute, and if you later need validation, turn it into a property — callers keep writing p.price and never notice:

python · try it yourself
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price          # goes through the setter below

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value

p = Product("Mouse", 15)
print(p.price)
p.price = 12
print(p.price)

try:
    p.price = -5
except ValueError as err:
    print("ValueError:", err)
print(p.price)
15
12
ValueError: price cannot be negative
12

Read-only and computed properties

A property without a setter is read-only. Properties can also compute their value from other attributes, so it never goes stale:

python · try it yourself
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

r = Rectangle(3, 4)
print(r.area)
r.width = 10
print(r.area)            # always up to date

try:
    r.area = 99
except AttributeError:
    print("area is read-only")
12
40
area is read-only

A fully encapsulated class

Here the internal list is kept private, and the public interface only offers safe operations:

python · try it yourself
class Wallet:
    def __init__(self):
        self._transactions = []

    def add(self, amount, note):
        if amount == 0:
            raise ValueError("amount must be non-zero")
        self._transactions.append((amount, note))

    @property
    def balance(self):
        return sum(amount for amount, _ in self._transactions)

    @property
    def transactions(self):
        return tuple(self._transactions)   # a read-only copy

w = Wallet()
w.add(500, "salary")
w.add(-120, "groceries")
w.add(-30, "coffee")
print(w.balance)
print(len(w.transactions))
print(w.transactions[1])
350
3
(-120, 'groceries')

Returning a tuple means callers can look at the history but can't append to the internal list directly.

Why encapsulate?

  • Validity: the object can enforce rules (no negative prices).
  • Freedom to change: you can change how data is stored internally without breaking code that uses the class.
  • Simplicity: users of the class see a small, clear interface.

Tip: Don't create properties "just in case". Plain attributes are perfectly Pythonic; switch to a property only when you need logic, and nobody's code has to change.

Test yourself

What does a single leading underscore, like _cache, signal?

  1. The attribute is truly private and inaccessible
  2. It's an internal detail by convention
  3. It's a class attribute
  4. It's a constant

What does @property let you do?

  1. Make a class abstract
  2. Access a method like an attribute, optionally with validation via a setter
  3. Create a static method
  4. Copy an object

What happens to an attribute named __secret inside class Box?

  1. It is deleted
  2. It becomes _Box__secret (name mangling)
  3. It becomes a constant
  4. Nothing special