A private member is an instance variable or method intended to remain an implementation detail of its class. In Python, a leading underscore marks that intention by convention rather than enforcement. Hiding state reduces dependencies: callers use the class interface without depending on how its state is stored. section 5.1 section 5.9
Use private members to control access and preserve implementation flexibility:
- Store state such as _name, _weight, and _price, then expose selected values through public properties. section 5.2
- Use a property setter when callers may change state; validate the new value before assigning it, so invalid state is rejected. section 5.2 section 5.9
- Keep helper methods private when they support the class’s own behavior, such as synchronizing alternate internal representations. section 5.3.3
- Avoid setters for immutable objects and avoid exposing references that would let callers mutate hidden state indirectly. section 5.9
Controlled price state
class Item:\n def __init__(self, name, weight, price):\n self._name = name\n self._weight = weight\n self._price = price\n\n @property\n def price(self):\n return self._price\n\n @price.setter\n def price(self, new_price):\n assert new_price > 0\n self._price = new_price\n\nCallers write item.price = 10.75 rather than assigning _price directly. The setter preserves the interface while rejecting a negative price; the class could later obtain prices from another hidden implementation without changing callers. section 5.2
Listing 5.1 (Program 5.1 DemeterItem): item.py
class Item:
def __init__(self, name, weight, price):
self._name = name #1
self._weight = weight #1
self._price = price #1
@property
def name(self): return self._name #2
@property
def weight(self): return self._weight #2
@property
def price(self): return self._price #2
@price.setter
def price(self, new_price): #3
assert new_price > 0
self._price = new_price
Inspect the complete Item example to see private initialization, public read-only properties, and validated mutation in a small Python class. section 5.2











