GGistDev

Inheritance in Python

Python supports single and multiple inheritance; method resolution order (MRO) determines lookup order.

Single inheritance

class Animal:
    def speak(self) -> str:
        return "..."

class Dog(Animal):
    def speak(self) -> str:
        return "woof " + super().speak()

super() calls parent implementations following MRO.

Multiple inheritance

Resolve via MRO (C3 linearization). Use mixins for orthogonal behaviors.

class LogMixin:
    def log(self, msg: str) -> None:
        print(msg)

class Service(Animal, LogMixin):
    pass

MRO and super

Inspect with Class.mro().

class A: pass
class B(A): pass
class C(B): pass
C.mro()  # [C, B, A, object]

With multiple inheritance:

class X: pass
class Y: pass
class Z(X, Y): pass
Z.mro()  # [Z, X, Y, object]

Abstract base classes (ABCs)

Define interfaces with abc.ABC and @abstractmethod.

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

Composition over inheritance

Prefer composition when sharing behavior across unrelated domains.

class Repo:
    def __init__(self, store):
        self.store = store

Best practices

  • Keep hierarchies shallow; use mixins for shared, small behaviors
  • Use super() consistently; ensure cooperative methods in multiple inheritance
  • Prefer composition when in doubt; avoid diamond complexity unless needed

Summary

  • Single/multiple inheritance supported; MRO governs lookup
  • Use ABCs for contracts, mixins for behavior, and composition to reduce coupling