On this page

Advanced OOP Patterns

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

The role of advanced OOP in real projects​

In small scripts, a few functions and classes are enough. In larger systems, you need structure: a way to add features, change behavior, and swap components without rewriting everything. Advanced OOP patterns are not “fancy tricks”; they are standard ways to organize code so that it remains understandable and changeable over time. Each pattern below is presented with a concrete problem and a direct solution.

Composition​

The problem it solves​

You want to build a class that uses several independent behaviors (logging, storage, validation), but you do not want a deep inheritance tree that is hard to change.

The idea​

Instead of inheriting from many classes, you give your class attributes that are other objects and call their methods.

Example and explanation​


class Logger:

    def log(self, message: str) -> None:

        print(message)



class Repository:

    def save(self, data: dict) -> None:

        print("Saving:", data)



class Service:

    def __init__(self, logger: Logger, repo: Repository) -> None:

        self.logger = logger

        self.repo = repo



    def run(self, payload: dict) -> None:

        self.logger.log("Service started")

        self.repo.save(payload)

        self.logger.log("Service finished")

Service does not inherit from Logger or Repository. It receives them as collaborators. To change logging or storage, you pass different objects. This keeps Service simple and testable.

Mixins​

The problem it solves​

You have a small feature (for example, “can export to JSON”) that you want to reuse across many unrelated classes without copying code.

The idea​

A mixin is a class that provides one focused behavior and is meant to be used together with another base class through multiple inheritance.

Example and explanation​


import json



class JSONExportMixin:

    def to_json(self) -> str:

        return json.dumps(self.__dict__)



class User(JSONExportMixin):

    def __init__(self, name: str) -> None:

        self.name = name



class Product(JSONExportMixin):

    def __init__(self, title: str, price: float) -> None:

        self.title = title

        self.price = price

User and Product both gain to_json() without repeating it. The mixin does not define its own __init__ and does not try to be a full type; it only adds a capability.

Abstract base classes​

The problem it solves​

You want several classes to follow the same interface (for example, all data sources must implement read()), and you want Python to enforce this at class definition time.

The idea​

An abstract base class (ABC) declares methods that subclasses must implement. Instantiating a subclass that does not implement them raises an error.

Example and explanation​


from abc import ABC, abstractmethod



class DataSource(ABC):

    @abstractmethod

    def read(self) -> str:

        ...



class FileDataSource(DataSource):

    def __init__(self, path: str) -> None:

        self.path = path



    def read(self) -> str:

        with open(self.path, encoding="utf-8") as f:

            return f.read()

DataSource defines the contract. Any subclass must implement read(). This allows you to write code that accepts a DataSource and works with files, APIs, or other sources without caring about the concrete type.

Protocols​

The problem it solves​

You want to accept any object that behaves in a certain way (for example, “has a write(str) method”), but you do not want to force inheritance from a specific base class.

The idea​

A protocol describes required methods and attributes. Static type checkers use it to verify compatibility; at runtime, any object with the right methods works.

Example and explanation​


from typing import Protocol



class Writer(Protocol):

    def write(self, data: str) -> None:

        ...



def log_message(writer: Writer, message: str) -> None:

    writer.write(message + "\n")

Any object with a write(str) -> None method can be passed to log_message: a file object, a custom logger, or an in‑memory buffer. This encourages designs based on behavior rather than inheritance.

Delegation​

The problem it solves​

You want to wrap an existing object to add behavior (logging, validation, caching) without modifying its class or changing how callers use it.

The idea​

Your wrapper object holds a reference to the real object and forwards calls to it, possibly adding extra steps.

Example and explanation​


class LoggingWriter:

    def __init__(self, inner) -> None:

        self.inner = inner



    def write(self, data: str) -> None:

        print("DEBUG:", repr(data))

        self.inner.write(data)

LoggingWriter can wrap any object with a write() method. Callers use it as if it were the original writer, but now every write is logged. This is a simple, explicit form of the decorator pattern.

Cooperative multiple inheritance and super​

The problem it solves​

You want to combine several mixins and base classes, each contributing to a method (for example, process()), without manually deciding which one to call next.

The idea​

Python computes a method resolution order (MRO). If each class uses super(), the call chain follows the MRO and every class gets a chance to run its part.

Example and explanation​


class BaseProcessor:

    def process(self, data: str) -> str:

        return data



class TrimMixin(BaseProcessor):

    def process(self, data: str) -> str:

        data = super().process(data)

        return data.strip()



class UpperMixin(BaseProcessor):

    def process(self, data: str) -> str:

        data = super().process(data)

        return data.upper()



class Pipeline(TrimMixin, UpperMixin):

    pass



p = Pipeline()

result = p.process("  hello  ")

# MRO: Pipeline -> TrimMixin -> UpperMixin -> BaseProcessor

super() ensures that TrimMixin calls UpperMixin, which calls BaseProcessor, in the correct order. This allows you to build pipelines of behavior using mixins.

Descriptors​

The problem it solves​

You want to control how an attribute behaves when it is set or accessed (for example, enforce validation, lazy loading, or computed values) in a reusable way.

The idea​

A descriptor is an object stored on the class that defines __get__, __set__, or __delete__. Python calls these methods when the attribute is accessed on instances.

Example and explanation​


class Positive:

    def __set__(self, instance, value: int) -> None:

        if value < 0:

            raise ValueError("Value must be non‑negative")

        instance.__dict__["balance"] = value



    def __get__(self, instance, owner):

        if instance is None:

            return self

        return instance.__dict__.get("balance", 0)



class Account:

    balance = Positive()



a = Account()

a.balance = 10      # validated by Positive.__set__

The logic for “must be non‑negative” lives in one place (Positive) and can be reused across many classes and attributes.

Metaclasses​

The problem it solves​

You want to enforce rules or perform actions when classes are defined (for example, automatically registering subclasses, checking required attributes, or modifying class attributes).

The idea​

A metaclass is the “class of a class.” When you define a class with a metaclass, Python calls the metaclass to create it. You can customize this creation step.

Example and explanation​


class Registry(type):

    registry = {}



    def __new__(mcls, name, bases, attrs):

        cls = super().__new__(mcls, name, bases, attrs)

        if name != "BaseService":

            mcls.registry[name] = cls

        return cls



class BaseService(metaclass=Registry):

    pass



class EmailService(BaseService):

    pass



class SMSService(BaseService):

    pass

Registry.registry now contains {"EmailService": EmailService, "SMSService": SMSService}. The registration happens automatically when the classes are defined, not when they are instantiated. This is useful for plugin systems and frameworks.

How to choose a pattern in practice​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Advanced Python

Next

Iterators & Custom Iterables