Encapsulation

Encapsulation is another programming pattern that often applies to modules and packages. Using encapsulation, you have a thing—for example, a color, a customer, or a currency—that you need to store data about, but you hide the representation of this data from the rest of your system. Rather than make the thing available directly, you provide functions for setting, retrieving, and manipulating the thing's data.

To see how this works, let's look back at a module we wrote in the previous chapter. Our chart.py module lets the user define a chart and set the various pieces of information about it. Here is a copy of the code that we wrote for this module:

def new_chart(): return {} def set_title(chart, title): chart['title'] = title def ...

Get Modular Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.