Jae Wilson @DataCrew

Using Inheritance + methods in Python to reduce code duplication

November 15, 2024

Hook

When two classes share the same fields and the same boilerplate methods, copying code between them isn't a design decision — it's a debt that compounds every time something changes.

Why It Matters

Without inheritance, identical logic like from_json, set_attribute, and to_json lives in multiple classes simultaneously. That means bug fixes applied to one class silently leave the other broken, and adding a shared field requires touching every subclass by hand. Pulling shared behavior into a base class makes the hierarchy self-documenting: any attribute or method on the parent is guaranteed to exist on every child, so you can write against the contract instead of the implementation.

What You'll Learn

  • Identify which attributes and methods belong on a base class versus a subclass
  • Write a parent from_json method that handles shared field extraction with pop, then let subclasses extend it
  • Use set_attribute and to_json on a base class so all variants inherit serialization behavior automatically
  • Apply the DRY principle to class hierarchies without losing the flexibility each subclass needs