Encapsulation groups related data and functions into a boundary that limits what other code needs to know. It reduces cognitive load by letting you focus on details only when they matter. section 3.2 section 3.0
Python uses classes, modules, and packages as progressively larger encapsulation constructs. A class contains methods and data; a module groups related classes and functions; a package groups related modules. section 3.2.1
Think of encapsulated code as a castle with a controlled drawbridge. Public methods form the interface, while internal behavior stays behind the boundary and can change without forcing dependent code to change. section 3.2.1 section 3.2.2
Good encapsulation keeps responsibilities focused and interfaces small:
- Separate related concerns into distinct, isolated pieces rather than letting every component depend on internal details. section 3.2.1
- In Python, prefix methods or variables intended for internal use with an underscore; this signals a convention rather than enforcing privacy. section 3.2.2
- Expose a clean entry point that coordinates internal steps, such as clean_query(query) instead of requiring callers to invoke each transformation. section 10.1.3
- Refactor boundaries as understanding improves; move behavior into standalone functions, another class, or a module when relationships become clear. section 3.3.1
Refactoring a Greeter
A Greeter initially exposes greet but keeps _day and _part_of_day as internal methods. Because greeting and date-time lookup are separate concerns, move those methods into module-level day() and part_of_day() functions. Greeter then calls the functions and focuses only on producing the greeting. The result has a narrower class responsibility and reusable date-time behavior. section 3.3 section 3.3.1
Figure 3.5. By decomposing a system into small parts, you can encapsulate behaviors and data into isolated pieces. Encapsulation encourages you to reduce the responsibilities of any given portion of code, helping you avoid complicated dependencies.
Use the decomposition diagram to see how behaviors and data become isolated pieces with fewer complicated dependencies. section 3.2.1













