๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

OOP Design Patterns and SOLID in Python Interviews

Python InterviewObject-Oriented Programmingโญ Premium
Python Interview ยท Difficulty: Medium-Hard

Why OOP questions are really design questions

When an interviewer asks you to "design a payment system" or "extend this logger," they are not grading your ability to recall the GoF catalogue by heart. They are watching how you carve a tangled requirement into small classes with clear boundaries, how you keep new features from rippling through existing code, and whether you exploit Python-specific tools โ€” duck typing, ABCs, descriptors, decorators โ€” instead of forcing Java habits onto a dynamic language. The winning move is to think out loud about responsibilities first, then sketch the classes, then show how a new requirement would be added without editing the classes you already wrote.

Prerequisites

  • !Classes, inheritance, and methods
  • !Exceptions and basic typing annotations

What You'll Learn

  • 1Map each SOLID principle onto a concrete Python refactor
  • 2Implement strategy, builder, factory-registry, observer, and command patterns idiomatically
  • 3Recognize when composition beats inheritance in Python
  • 4Answer the common follow-ups about MRO, ABCs versus duck typing, and dependency injection

Single responsibility: one sentence per class

The single responsibility principle says a class should have one reason to change. In practice that means a class either holds data, persists data, validates data, or coordinates a workflow โ€” not all four. A User entity that also opens database connections and sends welcome emails forces every consumer of that entity to depend on the database driver and the SMTP server. Splitting the same logic into User, UserRepository, EmailService, and a thin UserService that wires them together costs a few more files but lets you test the workflow with an in-memory repository and a fake mailer.

Python makes the seams easy to fake because nothing is truly private. A stub object with the same method names is a valid collaborator โ€” this is dependency injection without a framework. In an interview, say that explicitly: "I would pass the repository and mailer into the constructor so tests can substitute doubles." That single sentence demonstrates you have written production tests, which is often the real signal being sought.

Open for extension: strategy objects instead of conditionals

The open/closed principle is best demonstrated with the strategy pattern. Suppose payment processing branches on payment method with a growing if/elif chain. Each new method edits the same function, risking regressions in the branches you did not touch. Extract the branching into an abstract PaymentStrategy with concrete implementations for cards, PayPal, and crypto; the processor only knows the interface. Adding Apple Pay later means writing one new class and registering it โ€” the processor itself never changes.

Python's duck typing softens the need for a formal ABC, but the abstract base class still earns its place in interviews: it documents the contract, it fails fast if a subclass forgets a method, and it gives type checkers something to check. Show both โ€” mention that a Protocol would be the modern typing-native alternative โ€” and you demonstrate range.

python
from abc import ABC, abstractmethod


class PaymentStrategy(ABC):
    @abstractmethod
    def validate(self) -> bool:
        ...

    @abstractmethod
    def process(self, amount: float) -> bool:
        ...


class CardPayment(PaymentStrategy):
    def __init__(self, number: str, cvv: str):
        self.number, self.cvv = number, cvv

    def validate(self) -> bool:
        return len(self.number) == 16 and len(self.cvv) == 3

    def process(self, amount: float) -> bool:
        print(f"Charging {amount:.2f} to card ending {self.number[-4:]}")
        return True


class CryptoPayment(PaymentStrategy):
    def __init__(self, wallet: str):
        self.wallet = wallet

    def validate(self) -> bool:
        return len(self.wallet) >= 26

    def process(self, amount: float) -> bool:
        print(f"Broadcasting {amount:.2f} crypto to {self.wallet[:8]}...")
        return True


class Processor:
    def __init__(self, strategy: PaymentStrategy):
        self.strategy = strategy

    def checkout(self, amount: float) -> bool:
        if not self.strategy.validate():
            raise ValueError("invalid payment method")
        return self.strategy.process(amount)


processor = Processor(CardPayment("4111111111111111", "123"))
processor.checkout(49.99)

Creational patterns that Python developers actually use

The classic builder pattern solves the telescoping-constructor problem: a request object with eight optional fields should not force callers through positional soup or a pile of keyword defaults they might set wrongly. A fluent builder that returns self from each configuration method makes the construction read like a spec, and a build() method that validates required fields centralizes the invariants in one place.

The factory-registry variant is even more Pythonic: a class-level dict maps a format name to a serializer class, and create() instantiates on demand. Plugins register themselves at import time, so the factory never needs to know the full set of concrete classes. This is the pattern behind many configuration and plugin systems you will meet in real codebases.

For genuinely complex objects, consider dataclasses with a __post_init__ that validates, or keyword-only arguments with * to force callers to name their options. Interviewers respect candidates who know the standard tool before reaching for a pattern.

Behavioral patterns: observer and command

The observer pattern decouples an event source from its reactions. Implement a small EventEmitter with on, once, and emit, store listeners in a dict keyed by event name, and consider weakref.WeakMethod so forgotten listeners do not pin their objects in memory forever. Returning an unsubscribe function from on is a production-grade touch that shows you have debugged listener leaks.

The command pattern wraps an action as an object with execute and undo, enabling undo/redo stacks and audit logs. A text editor or a shopping cart is the usual demo: InsertCommand remembers what it inserted so undo can delete exactly that range. The history class owns an undo stack and a redo stack; executing a fresh command clears the redo stack, matching every GUI you have ever used.

python
from abc import ABC, abstractmethod


class Command(ABC):
    @abstractmethod
    def execute(self):
        ...

    @abstractmethod
    def undo(self):
        ...


class Cart:
    def __init__(self):
        self.items = []

    def add(self, sku: str):
        self.items.append(sku)

    def remove_last(self):
        return self.items.pop() if self.items else None


class AddItem(Command):
    def __init__(self, cart: Cart, sku: str):
        self.cart, self.sku = cart, sku

    def execute(self):
        self.cart.add(self.sku)

    def undo(self):
        self.cart.remove_last()


class History:
    def __init__(self):
        self._undo, self._redo = [], []

    def run(self, command: Command):
        command.execute()
        self._undo.append(command)
        self._redo.clear()

    def undo(self) -> bool:
        if not self._undo:
            return False
        command = self._undo.pop()
        command.undo()
        self._redo.append(command)
        return True

    def redo(self) -> bool:
        if not self._redo:
            return False
        command = self._redo.pop()
        command.execute()
        self._undo.append(command)
        return True

Python-specific tricks that impress interviewers

Descriptors power property, classmethod, and staticmethod; a brief mention that all three are descriptor objects under the hood earns credibility. Context managers implemented as classes or with contextlib.contextmanager show you understand resource safety. __slots__ is the standard answer when asked how to cut per-instance memory. And when the topic turns to class construction itself, __init_subclass__ gives you plugin auto-registration without a full metaclass โ€” most design questions stop there.

Duck typing also shapes how you design interfaces. Because Python checks that an object responds to a method rather than that it inherits from a specific base, you can accept any collaborator that implements the right operations โ€” including a simple types.SimpleNamespace or a test double. Protocols from the typing module document that structural contract for type checkers without forcing a shared ancestor. Interviewers who come from Java backgrounds often ask how Python enforces interfaces; the mature answer is that it enforces them late โ€” at call time โ€” and that ABCs or Protocols move that enforcement earlier for humans and tools.

How the patterns map to the SOLID principles

Interviewers sometimes ask which principle each pattern serves. Having a crisp mapping ready keeps you from rambling.

PatternPrimary SOLID principle it servesPythonic implementation note
StrategyOpen/ClosedPlain classes or functions; a Protocol documents the contract
BuilderSingle ResponsibilityFluent methods returning self; build() validates
Factory registryOpen/Closed, Dependency InversionClass-level dict; plugins self-register at import
ObserverSingle Responsibility, Dependency InversionStore callbacks loosely with weakref
CommandSingle ResponsibilityOne object per action; history owns the stacks
Decorator (class)Open/ClosedImplement __call__ and wrap with functools.wraps

Common Mistakes

Deep inheritance hierarchies to reuse code

Fix: Prefer composition; hold strategy or service objects and delegate

God classes that validate, persist, notify, and orchestrate

Fix: Split by reason to change and inject the collaborators

Forgetting functools.wraps when writing decorator classes or functions

Fix: Preserve __name__ and __doc__ so introspection and test names stay correct

Using a metaclass when __init_subclass__ would do

Fix: Reach for the simplest hook that solves the registration problem

Best Practices

  • Sketch responsibilities on the board before writing any class
  • Prefer keyword-only arguments or a builder when constructors exceed three or four parameters
  • Show at least one test seam โ€” a fake repository, a stub strategy โ€” when you present your design
  • Name the trade-off you are accepting; interviewers reward awareness over perfection

Interview Questions

Q1: Composition or inheritance โ€” when do you choose which?

Inheritance models an is-a relationship and is fine for true specializations. Composition models has-a and wins when behavior needs to vary independently or be swapped at runtime; it keeps coupling low and testing easy.

Q2: How does Python's method resolution order work with multiple inheritance?

C3 linearization produces a consistent order: the class itself, then bases left to right, depth first, with no class appearing before any of its subclasses. You can inspect it via the __mro__ attribute or the mro() method.

Q3: Abstract base classes versus duck typing โ€” why bother with ABCs?

Duck typing is flexible but silent about the contract. ABCs document required methods, raise TypeError at instantiation if methods are missing, and integrate with static type checkers. Protocols offer structural typing when you cannot modify the class hierarchy.

Q4: How would you implement dependency injection in a plain Python app?

Accept collaborators as constructor or method parameters, default them to real implementations at composition roots, and let tests pass fakes. Frameworks like dependency-injector exist, but constructor injection is usually enough.

Q5: Class methods, static methods, and instance methods โ€” when is each appropriate?

Instance methods access per-object state through self. Class methods receive the class and work well as alternative constructors or class-aware factories. Static methods are namespaced functions that need no access to the class or instance.

Key Takeaways

  • OOP interviewers are grading boundary-drawing, not GoF recitation
  • SOLID maps cleanly onto Python: strategy for open/closed, split classes for single responsibility, ABCs for contracts
  • Composition with injected collaborators beats deep inheritance for testability
  • Observer and command patterns show up in event systems and undo stacks; know both
  • Pythonic extras โ€” descriptors, context managers, __init_subclass__, __slots__ โ€” separate senior answers from textbook ones
  • Always state the trade-off your design accepts
๐Ÿ”’

Premium Content

OOP Design Patterns and SOLID in Python Interviews

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement