Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 09 / Topic 4 of 12

Encapsulation: _protected, __private, @property

Encapsulation means an object protects its own data. Code outside should use the object's methods, not change its insides directly. Python has no hard locks. It uses naming habits instead:

Name Meaning
price Public: anyone may use it
_price "Protected": a hint that says "internal, please do not touch from outside"
__price "Private": Python renames it to _ClassName__price (name mangling) so it is hard to reach by accident

Think of an ATM: you press buttons (methods), but you cannot open the cash box (internal data).

class Locker:
    def __init__(self, owner: str, pin: int):
        self.owner = owner       # public
        self._items = []         # protected by habit
        self.__pin = pin         # private: becomes _Locker__pin

    def open(self, pin: int) -> bool:
        return pin == self.__pin

box = Locker("Kiran", 4321)
print(box.open(1111))            # False
print(box._items)                # [] (works, but you should not do this)
# box.__pin -> AttributeError: 'Locker' object has no attribute '__pin'

@property: an attribute with a check

A property looks like a plain attribute from outside (item.price), but runs a method each time you read or set it. Use it to validate values (check them before saving).

  • @property above a method makes the getter (runs when you read the value).
  • @<name>.setter above a second method with the same name makes the setter (runs when you assign a value).
class Product:
    def __init__(self, name: str, price: float):
        self.name = name
        self.price = price           # goes through the setter below

    @property
    def price(self) -> float:        # getter
        return self._price

    @price.setter
    def price(self, value: float) -> None:   # setter
        if value < 0:
            raise ValueError("Price cannot be negative")
        self._price = value

pen = Product("Gel pen", 20)
pen.price = 25                       # looks like a plain assignment
print(pen.price)                     # 25
try:
    pen.price = -5
except ValueError as e:
    print("Error:", e)               # Error: Price cannot be negative

The real value is stored in self._price. The property price is the public door to it. A property with no setter is read-only: assigning to it raises AttributeError.

Full program: examples/02_product_property.py.

๐Ÿ” Going deeper: start with plain public attributes. Turn one into a property later only when you need a check; the code that uses pen.price does not need to change. Use __private rarely, mainly to avoid name clashes in child classes.

Done here? The practice set for Part 9 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide