Every value manipulated in this vault so far — an
int, a list, a dict — has been an instance of an abstract data type: a set of objects bundled together with the operations defined on them, used without ever needing to know how those operations are implemented internally. This has been true from the first lesson, even though the term was never used. This note names the idea explicitly and shows how to build a class — Python's mechanism for defining new abstract data types of your own — using a small worked example, IntSet, a set of integers built from scratch on top of a list. Every later class in this unit builds on the vocabulary introduced here: instances, methods, self, data attributes, and the representation invariant.Learning objectives. By the end of this note you should be able to:
- explain what an abstract data type is, and why the "interface hides the implementation" idea is simply decomposition and abstraction (from Specifications and Top-Down Design) applied to a bundle of data and operations together, rather than a single function;
- write a class with
__init__, instance methods, and theselfparameter, and correctly instantiate and call methods on objects of that class; - distinguish a class attribute from an instance attribute, and a method attribute from a data attribute;
- state a representation invariant for a class, and explain how each method is responsible for preserving it.
In this lesson
- Abstract data types: an interface over an implementation
- Building a class:
IntSet - Instantiation and attribute access
- Class attributes vs. instance attributes; representation invariants
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.