Skip to content
Python for Quantitative Finance / Object-Oriented Programming

Encapsulation and Information Hiding

The two previous notes built classes and a hierarchy of them, but never stopped to ask: what, exactly, should a class's clients be allowed to see and touch directly? Encapsulation — bundling data and the methods that operate on it — has been implicit since Abstract Data Types and Classes's first class block. Information hiding, this note's central idea, goes further: restricting a client's access to a class's internal data so that the class's implementation can change freely without breaking client code that only ever relied on the class's specified interface. This note builds a small Grades class to show the practical payoff, covers Python's (deliberately weak) __-prefixed naming convention for hiding attributes, and introduces generators as the efficient alternative to returning a full list from a method whose caller only needs to iterate over the results once.
Learning objectives. By the end of this note you should be able to:
  • explain why methods like get_grades and get_students return a copy of an internal list rather than the list itself, connecting this to the aliasing discussion from Lists and Mutability;
  • use Python's __-prefixed naming convention for attributes, and state precisely what it does and does not enforce;
  • explain why this vault (following Guttag's own convention) generally avoids directly accessing instance attributes from outside a class, even though Python does not strictly enforce this;
  • write a generator method using yield, and explain the efficiency advantage it offers over building and returning a full list.

In this lesson

  1. A worked example: Grades
  2. Encapsulation vs. information hiding
  3. Generators: efficient iteration without a full list

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.