bhylu.com

Advertisements

Encapsulation

Encapsulation keeps an object's state changes behind a clear interface so its invariants can be maintained. In Python, conventions and properties provide most ordinary encapsulation tools.

Understand the idea

A leading underscore marks an internal detail for cooperative callers. Double-leading-underscore names trigger name mangling, mainly to reduce accidental subclass collisions; they are not secure storage. A reserve method can reject invalid requests before changing stock, keeping that rule in one place rather than depending on every caller to repeat it.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Stock:
    def __init__(self, count):
        self._count = count
    def reserve(self, amount):
        if amount <= 0 or amount > self._count:
            raise ValueError("Invalid reservation")
        self._count -= amount
    @property
    def count(self):
        return self._count

stock = Stock(8)
stock.reserve(3)
print(stock.count)

Read the result

The count becomes 5 through the controlled reservation operation.

Try one change

Test an excessive reservation and confirm the original count is preserved when validation fails.