Abstract Data Types and Classes built a single, standalone class. Many real problems, though, involve a family of related types that share most of their behaviour but differ in a specific way — an undergraduate and a graduate student are both students, sharing most attributes, but differing in what data they carry. Inheritance lets a new class (a subclass) reuse an existing class's (a superclass's) attributes and methods, adding new ones and selectively overriding existing ones. This note builds a small
Person → MITPerson → Student → UG/Grad hierarchy to show exactly how attribute lookup, overriding, and isinstance work together — and closes with the substitution principle, the design rule that keeps an inheritance hierarchy trustworthy rather than a source of subtle bugs.Learning objectives. By the end of this note you should be able to:
- define a subclass that inherits from a superclass, calling the superclass's
__init__explicitly to reuse its initialisation logic; - explain method overriding, and correctly predict which version of an overridden method Python invokes for a given object;
- use
isinstancecorrectly, distinguishing it from a directtype(x) == SomeClasscheck, and explain whyisinstanceis usually the more maintainable choice; - state the substitution principle and identify when a subclass's overriding of a method violates it.
In this lesson
- A base class:
Person - Subclassing: reusing and extending a superclass
- Multiple levels:
isinstancevs.type() == - The substitution principle
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.