An accessor method lets client code read an object's state through a public interface without depending on the hidden representation. A getter may return a private instance variable today and obtain the same value from another source, such as a database, later. section 5.2
Use accessors to control how state is observed and changed:
- Define a getter with @property so callers can write item.price rather than access item._price. section 5.2
- Add a setter only when mutation is justified, and validate new values before changing hidden state. section 5.2 section 5.4
- Avoid setters that update related fields independently when intermediate combinations can make the object invalid. section 5.5
- Return copies from getters when the returned object is mutable and the enclosing object must remain immutable. section 5.7
A validated property
class Item: def __init__(self, price): self._price = price @property def price(self): return self._price @price.setter def price(self, new_price): assert new_price > 0 self._price = new_price item = Item(10.31) item.price = 10.75 # accepted item.price = -9.99 # AssertionError 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 implementation, including public properties, hidden fields, and the validating price setter. section 5.2












