Abstract Base Classes and Method Binding in Python

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Consider the following Python class sketch for financial contracts:

class Instrument:
    def price(self, curve): ...

    @classmethod
    def from_record(cls, record): ...

    @staticmethod
    def is_valid_quantity(quantity): ...

Explain both object-oriented Python topics illustrated here (for concreteness, you may trace a concrete child class such as a $1,000-par TreasuryStrip "UST-3Y" holding quantity=4 and maturity=3.0 on a 4% annual discount curve):

  1. Abstract base classes:
    • What problem does an abstract class solve?
    • How do you declare one in Python, can you instantiate it directly, and at what exact stage does Python reject invalid instantiation?
    • What must a child class do before callers can create instances of it?
  2. Instance, class, and static methods:
    • How do ordinary instance methods, @classmethod definitions, and @staticmethod definitions differ in what Python passes automatically?
    • What do self and cls refer to, and are those names language keywords or conventions?
    • Since a @staticmethod receives neither an object instance nor a class reference, why place it on a class rather than at module scope?

Scope & Expectations

  • Explaining how abc.ABC and @abstractmethod pair an enforced subclass contract with shared concrete methods, and pinpointing when TypeError is raised.
  • Contrasting implicit first-argument binding (self, cls, or nothing), accessible state, and PEP 8 naming conventions across all three method types.
  • Demonstrating canonical use cases—per-instance calculations, subclass-aware factory constructors, and cohesive validation helpers—with a concrete worked example.
  • Tracing how inheritance and method overrides behave across instance, class, and static methods.

Step-by-step walkthrough

  1. Understand why abstract classes exist

    An abstract class is a blueprint class designed to be inherited from, not instantiated directly. It solves two problems at once for a family of related types (such as bonds, swaps, and futures inheriting from Instrument):

    1. Enforces a shared interface: An interface is the guaranteed set of method names and signatures callers can rely on (for example, "every Instrument has a .price(curve) method"), even when the base class cannot write the formula itself because bonds and options are priced differently.
    2. Reuses shared implementation: Unlike a pure interface, an abstract class can provide ordinary concrete methods (market_value = quantity * price), validation, and constructors once in the base class so subclasses inherit them for free.

    Why forbid direct instantiation? Imagine someone accidentally runs inst = Instrument(...) on a plain base class where price is missing or raises NotImplementedError. The broken object enters a portfolio list quietly and crashes much later during a nightly risk batch, far from where it was created. Marking Instrument abstract moves that error to the earliest moment Python can check: the exact line that tries to construct Instrument(...).

    (If the interviewer compares languages: Java's abstract class and C++'s pure virtual virtual double price() = 0; reject new Instrument() at compile time. Because Python defines classes dynamically without a separate compile step, Python enforces the check at run time during object creation.)

  2. Declare an abstract class with abc and see when it fails

    In Python, inherit from abc.ABC (which sets the class's metaclass—the factory that builds classes—to ABCMeta) and decorate each required method with @abstractmethod:

    from abc import ABC, abstractmethod
    
    
    class Instrument(ABC):
        def __init__(self, symbol: str, quantity: int, maturity: float):
            if not self.is_valid_quantity(quantity):
                raise ValueError(f"invalid quantity: {quantity}")
            self.symbol = symbol
            self.quantity = quantity
            self.maturity = maturity  # years until maturity
    
        @abstractmethod
        def price(self, curve) -> float:
            """Unit price of the instrument given a discount curve (years -> factor)."""
    
        def market_value(self, curve) -> float:
            # Concrete method shared by all subclasses; calls subclass's price()
            return self.quantity * self.price(curve)
    
        @classmethod
        def from_record(cls, record: dict[str, str]):
            # Alternative constructor: cls is whichever subclass this was called on
            return cls(
                symbol=record["symbol"],
                quantity=int(record["quantity"]),
                maturity=float(record["maturity"]),
            )
    
        @staticmethod
        def is_valid_quantity(quantity) -> bool:
            # bool subclasses int in Python (isinstance(True, int) is True!), so exclude bool
            return isinstance(quantity, int) and not isinstance(quantity, bool) and quantity != 0
    

    Pinpoint the exact lifecycle so you can answer "When and how does instantiation fail?" with precision:

    1. Class definition (`class Instrument(ABC): ...` executes at import time)
       --> SUCCEEDS. ABCMeta records Instrument.__abstractmethods__ = frozenset({'price'}).
    
    2. Instantiation attempt (`Instrument("UST-3Y", 4, 3.0)` executes at run time)
       --> FAILS inside object.__new__ BEFORE __init__ ever runs!
       --> Raises TypeError: Can't instantiate abstract class Instrument without an
           implementation for abstract method 'price'
    

    Watch out for two common abc subtleties: - Both pieces are required: Putting @abstractmethod on a plain class that does not inherit from ABC (or use metaclass=ABCMeta) does nothing at all—Python silently lets callers instantiate it! - Inheriting from ABC alone does not block instantiation: If a class inherits from ABC and defines zero @abstractmethods, __abstractmethods__ is empty (frozenset()), so Python allows instantiating it normally.

  3. Implement a concrete subclass with a worked example

    A subclass becomes concrete (instantiable) as soon as it overrides every @abstractmethod inherited from its base classes. Everything else—__init__, market_value, from_record, and is_valid_quantity—works automatically:

    class TreasuryStrip(Instrument):
        FACE_VALUE = 1000.0
    
        def price(self, curve) -> float:
            # Discount the $1,000 par value back from maturity to today
            return self.FACE_VALUE * curve(self.maturity)
    
    
    def flat_four_pct_curve(years: float) -> float:
        """Discount factor (today's value of $1 paid in `years` at 4% annual rate)."""
        return 1.0 / (1.04 ** years)
    

    Trace a concrete 3-year treasury strip ("UST-3Y") with quantity = 4 on the 4% curve:

    strip = TreasuryStrip("UST-3Y", quantity=4, maturity=3.0)
    
    1. flat_four_pct_curve(3.0)   = 1 / (1.04 ^ 3) = 1 / 1.124864 = 0.888996...
    2. strip.price(curve)         = 1000.0 * 0.888996...          = 888.996358... (~$889.00 per strip)
    3. strip.market_value(curve)  = 4 * 888.996358...             = 3555.9854...  (~$3,555.99 total)
    

    Notice step 3: TreasuryStrip never defined market_value, yet calling strip.market_value(flat_four_pct_curve) runs Instrument.market_value and dynamically dispatches self.price(curve) to TreasuryStrip.price!

    (Note: if a subclass implements only some of its parent's abstract methods, it stays abstract itself—useful for intermediate base classes like Bond(Instrument)—and note that an @abstractmethod in Python is allowed to have a body that subclasses can invoke via super().)

  4. Instance methods and what self really is

    A normal def inside a class defines an instance method. When you access strip.price on an instance, Python uses its descriptor protocol (the lookup hook that controls how attributes behave when read from a class vs an instance) to wrap the function and strip together into a bound method object, automatically passing strip as the first argument:

    What you write:              strip.price(flat_four_pct_curve)
                                   |
                                   v  (bound method prepends `strip` as argument #1)
    What Python actually runs:   TreasuryStrip.price(strip, flat_four_pct_curve)
    

    Therefore: - self is the specific object instance the method was called on. - What self can access: Both per-object attributes stored in self.__dict__ (self.symbol, self.quantity, self.maturity) and class attributes/methods (self.FACE_VALUE, self.price), always starting lookup at type(self) so subclass overrides win. - self is a naming convention, not a Python keyword: Writing def price(this, curve): behaves identically at runtime—only being the first parameter matters—though deviating from self violates PEP 8 and confuses every Python reader.

  5. Class methods, cls, and alternative constructors

    Decorating a method with @classmethod changes what Python passes as the first implicit argument: instead of an instance, Python passes the class object itself (cls)—whether you call TreasuryStrip.from_record(r) on the class or strip.from_record(r) on an instance (cls receives type(strip)).

    Like self, the name cls is a universal PEP 8 convention (class cannot be used because it is a reserved keyword). Because cls receives no instance, a class method cannot read per-object attributes like self.maturity, but it can read class attributes (cls.FACE_VALUE) and construct new instances via cls(...).

    The #1 practical job for @classmethod is writing alternative constructors—factory methods that parse an object from an alternate format (a CSV dict, JSON payload, or ISO string) while automatically building the right subclass:

    raw_row = {"symbol": "UST-2Y", "quantity": "5", "maturity": "2"}
    strip_2y = TreasuryStrip.from_record(raw_row)
    
    assert type(strip_2y) is TreasuryStrip
    # 2-year price at 4%: 1000 / (1.04 ^ 2) = 1000 / 1.0816 = 924.5562... (~$924.56)
    assert round(strip_2y.price(flat_four_pct_curve), 2) == 924.56
    

    Look at why cls(...) inside Instrument.from_record is magic: we wrote from_record once in Instrument, yet calling TreasuryStrip.from_record(raw_row) passes cls = TreasuryStrip and returns a TreasuryStrip! Meanwhile, calling Instrument.from_record(raw_row) passes cls = Instrument, which immediately hits the abstract-class TypeError—protecting the invariant from factory calls too. Standard-library examples include dict.fromkeys(["a", "b"], 0) and datetime.fromisoformat("2026-11-30").

  6. Static methods and why they belong inside a class

    Decorating a method with @staticmethod disables implicit first-argument binding altogether: Python passes neither self nor cls. Whether you call Instrument.is_valid_quantity(4) on the class or strip.is_valid_quantity(4) on an instance, the function receives only (4,).

    That immediately prompts the interviewer's best question: "If a static method receives neither the instance nor the class, why put it inside the class instead of making it a standalone module-level function?" Two concrete reasons justify @staticmethod:

    1. Cohesion and discoverability: "What counts as a valid Instrument quantity?" belongs conceptually to Instrument. Grouping it inside Instrument keeps related domain rules together in help(Instrument) and avoids polluting module namespaces or requiring extra imports.
    2. Polymorphic overriding in subclasses: When __init__ calls self.is_valid_quantity(quantity) (instead of calling a module-level function _is_valid_quantity(quantity)), a subclass can override the rule without rewriting __init__!
    class LongOnlyStrip(TreasuryStrip):
        @staticmethod
        def is_valid_quantity(quantity) -> bool:
            # Tighten parent's != 0 rule: disallow negative (short) positions too
            return isinstance(quantity, int) and not isinstance(quantity, bool) and quantity > 0
    
    
    short_ok = TreasuryStrip("UST-3Y", quantity=-5, maturity=3.0)   # succeeds: -5 != 0
    # LongOnlyStrip("UST-3Y", quantity=-5, maturity=3.0)            # raises ValueError!
    

    When a utility function is genuinely generic (such as clamp(x, lo, hi) or date math unrelated to instruments), put it at module level instead—unlike Java, Python never forces unrelated helpers into utility classes.

  7. Compare all three method kinds side by side

    Keep this mental lookup table ready for quick oral follow-ups:

    Method kind       Decorator       Implicit 1st arg   Can access          Primary use & inheritance behavior
    ----------------  --------------  -----------------  ------------------  ------------------------------------------
    Instance method   (none)          self (instance)    Instance + class    Per-object behavior (`price`, `market_value`);
                                                         state & methods     dispatches via type(self), supports super()
    Class method      @classmethod    cls (the class)    Class state &       Alternative constructors (`from_record`),
                                                         cls(...) factories  class registries; `cls` is calling subclass
    Static method     @staticmethod   (none)             Only explicit args  Domain helper (`is_valid_quantity`); overrides
                                                                             work ONLY when called via `self.` or `cls.`
    

    A compact 20-line verification snippet confirms every binding rule in one glance:

    class Probe:
        def instance_m(self):
            return self
    
        @classmethod
        def class_m(cls):
            return cls
    
        @staticmethod
        def static_m(*args):
            return args
    
    
    class ChildProbe(Probe):
        pass
    
    
    obj = ChildProbe()
    assert obj.instance_m() is obj                                  # receives the instance
    assert obj.class_m() is ChildProbe                              # receives instance's class
    assert ChildProbe.class_m() is ChildProbe                       # receives the subclass itself
    assert obj.static_m("x") == ("x",)                              # no implicit first arg
    assert ChildProbe.static_m("x") == ("x",)                       # identical via class
    

Intuition & how it works

Picture a financial franchise binder for pricing market instruments. An abstract class (Instrument) is the master template in that binder: it gives every branch ready-to-use accounting formulas (market_value = quantity × unit_price) and order-intake forms (from_record), while leaving a mandatory [Insert pricing formula here] blank that prevents anyone from opening a generic "Instrument" trade without choosing a real product like TreasuryStrip. Inside that class, the three method kinds simply decide how much context Python hands the function automatically: - Instance method (def price(self, curve)): Needs this specific strip (self) to read its maturity (3.0 years). - Class method (@classmethod def from_record(cls, row)): No strip exists yet—needs which class blueprint to build (cls, e.g., TreasuryStrip). - Static method (@staticmethod def is_valid_quantity(qty)): Needs neither—just checks a standalone rule (qty != 0) attached to the class's rulebook.

Without these tools, naive OOP designs fail in predictable ways. Writing a plain base class whose price raises NotImplementedError lets callers instantiate half-baked Instrument objects that sit silently in memory until a late report crashes; and writing a factory helper that hardcodes return Instrument(...) instead of using @classmethod with cls(...) either builds the wrong parent type or crashes when subclasses inherit it.

Walk through one concrete TreasuryStrip trace (FACE_VALUE = 1000, 4% discount curve 1 / 1.04^years) using all four pieces together: - Abstract guard: Calling Instrument("UST-3Y", 4, 3.0) fails immediately at object creation with TypeError because price is still abstract. - Class method (cls): Calling TreasuryStrip.from_record({"symbol": "UST-3Y", "quantity": "4", "maturity": "3"}) passes cls = TreasuryStrip into Instrument.from_record, runs self.is_valid_quantity(4) (True), and constructs a TreasuryStrip instance. - Instance methods (self): Calling strip.market_value(curve) runs the inherited Instrument.market_value(strip, curve), which calls strip.price(curve) → 1000 × (1 / 1.04^3) = 888.9963... and multiplies by strip.quantity (4) to return 3555.99.

Key points

  • Purpose of an abstract class: Combines a mandatory interface (abstract methods every concrete subclass must implement) with shared concrete code (__init__, market_value) written in terms of those methods.
  • How Python enforces it—and when: Inherit from abc.ABC (which uses metaclass ABCMeta) and decorate required methods with @abstractmethod. Defining the class succeeds; instantiating it (Instrument(...)) raises TypeError at run time inside object.__new__ before __init__ runs (unlike Java/C++, which fail at compile time).
  • Making a subclass instantiable: A subclass must override every inherited @abstractmethod; leaving even one unimplemented keeps the subclass abstract.
  • Instance methods & self: Receive the object instance (self) via a bound method created by Python's descriptor protocol (strip.price(c) becomes TreasuryStrip.price(strip, c)), giving access to both per-instance state (self.maturity) and class attributes/methods.
  • Class methods & cls: Decorated with @classmethod; receive the class object (cls), whether called on the class or an instance. Essential for alternative constructors (from_record, dict.fromkeys, datetime.fromisoformat) so inherited factories instantiate the calling subclass (cls(...)).
  • Static methods: Decorated with @staticmethod; receive neither self nor cls. Used inside a class for namespace cohesion/discoverability and so subclasses can override helper rules when invoked through self.helper(...) or cls.helper(...).
  • self and cls are conventions, not keywords: Python binds by parameter position (first argument), though PEP 8 universally mandates the names self and cls.

Common mistakes

  • Using @abstractmethod without ABC (or ABCMeta): On a plain class class Foo:, @abstractmethod does not prevent Foo() from instantiating—ABCMeta is what checks __abstractmethods__ at creation time.
  • Assuming class Empty(ABC): pass cannot be instantiated: Inheriting from ABC with zero unimplemented @abstractmethods leaves __abstractmethods__ empty, so Empty() succeeds.
  • Stacking @abstractmethod in the wrong order: When combining decorators (such as @classmethod or @property with @abstractmethod), @abstractmethod must be the innermost decorator right above def, or ABCMeta may fail to register it properly.
  • Hardcoding the class name inside a factory method: Writing return BaseClass(...) instead of @classmethod + return cls(...) returns a base instance (or raises TypeError if the base is abstract!) when called as SubClass.from_record(...).
  • Bypassing static-method overrides via hardcoded class names: Calling Instrument.is_valid_quantity(q) inside __init__ ignores any override on LongOnlyStrip; call self.is_valid_quantity(q) or cls.is_valid_quantity(q) so polymorphism works.
  • Forgetting bool subclasses int in Python validation helpers: isinstance(True, int) evaluates to True (True == 1), so integer validators should guard not isinstance(x, bool).

Follow-up questions

  • When a child class calls an inherited @classmethod factory, which class gets instantiated, and how would switching that factory to @staticmethod break subclassing? Called as TreasuryStrip.from_record(record), Python passes cls = TreasuryStrip, so return cls(...) constructs and returns an instance of TreasuryStrip even though from_record was defined on Instrument. If from_record were a @staticmethod, Python would pass no cls parameter, forcing the body to hardcode a class name: hardcoding TreasuryStrip(...) breaks sibling subclasses like Swap, while hardcoding Instrument(...) immediately crashes with TypeError because Instrument is abstract!

  • Suppose a base class declares multiple @abstractmethod hooks and a child class overrides only one of them—what happens at class-definition time versus instantiation time? Suppose Instrument declares two abstract methods, price(self, curve) and duration(self, curve), and PartialStrip(Instrument) implements price without implementing duration. Defining class PartialStrip(Instrument): succeeds with zero error, PartialStrip.__abstractmethods__ holds frozenset({'duration'}), and any attempt to instantiate PartialStrip(...) raises TypeError: Can't instantiate abstract class PartialStrip without an implementation for abstract method 'duration'. In larger hierarchies, engineers intentionally write partial subclasses (like Bond(Instrument)) as intermediate building blocks for concrete leaves (TreasuryStrip(Bond)).

  • In what design scenarios is structural typing with typing.Protocol preferable to inheriting from an abc.ABC base class? An ABC uses nominal subtyping (a class conforms only by explicitly inheriting class MyStrip(Instrument):), giving you shared concrete methods (market_value) and strict runtime instantiation guards. typing.Protocol uses structural subtyping (static duck typing: any class with a matching def price(self, curve) -> float: conforms automatically without inheriting anything), verified before runtime by type checkers like mypy or pyright. Reach for Protocol when decoupling libraries, typing third-party classes you cannot modify, or keeping lightweight test fakes inheritance-free; reach for ABC when subclasses genuinely share implementation code or need runtime instantiation protection.

  • If count = 0 is defined on the class body and an instance method executes self.count += 1, how do the instance dictionary and the class attribute change? Because count = 0 is an immutable integer on the class, the class attribute stays 0! Python expands self.count += 1 into self.count = self.count + 1: the right-hand read self.count misses self.__dict__ and falls back to TradeCounter.count (0), computes 0 + 1 = 1, and then the assignment writes 'count': 1 into self.__dict__, creating an instance attribute that shadows (hides) the class attribute for that one object. To increment a true class-wide counter, write type(self).count += 1 (or cls.count += 1 in a @classmethod); and beware mutable class attributes like items = [], where self.items += [x] mutates the single shared list in place across all instances and binds self.__dict__['items'] to that same shared list!

```python class TradeCounter: count = 0 # class attribute shared on TradeCounter

  def bump_wrong(self):
      # Reads TradeCounter.count (0) on first call, then writes self.__dict__["count"]!
      self.count += 1

  def bump_shared(self):
      # Explicitly mutates the attribute on the class itself
      type(self).count += 1

t1, t2 = TradeCounter(), TradeCounter() t1.bump_wrong() t1.bump_wrong() assert t1.count == 2 and t2.count == 0 and TradeCounter.count == 0

t1.bump_shared() assert t2.count == 1 and TradeCounter.count == 1 ```

Follow-up questions

Similar questions

More Engelhart interview questions

All 8 Engelhart questions →