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

Inheritance and Method Overriding

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 isinstance correctly, distinguishing it from a direct type(x) == SomeClass check, and explain why isinstance is usually the more maintainable choice;
  • state the substitution principle and identify when a subclass's overriding of a method violates it.

In this lesson

  1. A base class: Person
  2. Subclassing: reusing and extending a superclass
  3. Multiple levels: isinstance vs. type() ==
  4. The substitution principle

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.