Encapsulation exposes only the interface that other code needs while hiding a class’s implementation. In Python, a class groups instance variables and methods, and private members restrict direct access. The broader design principle, “Encapsulate What Varies,” isolates change so implementation updates do not spread through dependent classes. section 1.8 section 5.0 section 1.10
Apply encapsulation by:
- Making instance variables and methods private when clients do not need direct access. section 5.0
- Exposing only the public members required by other classes. section 5.0
- Isolating behavior likely to change so clients remain unaffected when implementation details change. section 1.10
Date implementation hiding
A Date object represents a calendar date with year, month, and day values. Keeping _year, _month, and _day private lets the class hide its representation while providing operations such as date arithmetic through its interface. Client code depends on Date’s behavior rather than on how dates are stored. section 5.3
The cost of missing encapsulation
In the poorly designed sports application, Baseball and Football both hardcode the stadium venue. If that venue changes, multiple subclasses must change; duplicated algorithms are difficult to reuse and maintain. Encapsulating varying algorithms supports looser coupling and avoids these change leaks. section 8.2.2













