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):
- 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?
- Instance, class, and static methods:
- How do ordinary instance methods,
@classmethoddefinitions, and@staticmethoddefinitions differ in what Python passes automatically? - What do
selfandclsrefer to, and are those names language keywords or conventions? - Since a
@staticmethodreceives neither an object instance nor a class reference, why place it on a class rather than at module scope?
- How do ordinary instance methods,
Scope & Expectations
- Explaining how
abc.ABCand@abstractmethodpair an enforced subclass contract with shared concrete methods, and pinpointing whenTypeErroris 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
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):- Enforces a shared interface: An interface is the guaranteed set of method names and signatures callers can rely on (for example, "every
Instrumenthas a.price(curve)method"), even when the base class cannot write the formula itself because bonds and options are priced differently. - 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 wherepriceis missing or raisesNotImplementedError. The broken object enters a portfolio list quietly and crashes much later during a nightly risk batch, far from where it was created. MarkingInstrumentabstract moves that error to the earliest moment Python can check: the exact line that tries to constructInstrument(...).(If the interviewer compares languages: Java's
abstract classand C++'s pure virtualvirtual double price() = 0;rejectnew Instrument()at compile time. Because Python defines classes dynamically without a separate compile step, Python enforces the check at run time during object creation.)- Enforces a shared interface: An interface is the guaranteed set of method names and signatures callers can rely on (for example, "every
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—toABCMeta) 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 != 0Pinpoint 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
abcsubtleties: - Both pieces are required: Putting@abstractmethodon a plain class that does not inherit fromABC(or usemetaclass=ABCMeta) does nothing at all—Python silently lets callers instantiate it! - Inheriting fromABCalone does not block instantiation: If a class inherits fromABCand defines zero@abstractmethods,__abstractmethods__is empty (frozenset()), so Python allows instantiating it normally.Implement a concrete subclass with a worked example
A subclass becomes concrete (instantiable) as soon as it overrides every
@abstractmethodinherited from its base classes. Everything else—__init__,market_value,from_record, andis_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") withquantity = 4on 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:
TreasuryStripnever definedmarket_value, yet callingstrip.market_value(flat_four_pct_curve)runsInstrument.market_valueand dynamically dispatchesself.price(curve)toTreasuryStrip.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@abstractmethodin Python is allowed to have a body that subclasses can invoke viasuper().)Instance methods and what self really is
A normal
definside a class defines an instance method. When you accessstrip.priceon 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 andstriptogether into a bound method object, automatically passingstripas 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: -
selfis the specific object instance the method was called on. - Whatselfcan access: Both per-object attributes stored inself.__dict__(self.symbol,self.quantity,self.maturity) and class attributes/methods (self.FACE_VALUE,self.price), always starting lookup attype(self)so subclass overrides win. -selfis a naming convention, not a Python keyword: Writingdef price(this, curve):behaves identically at runtime—only being the first parameter matters—though deviating fromselfviolates PEP 8 and confuses every Python reader.Class methods, cls, and alternative constructors
Decorating a method with
@classmethodchanges what Python passes as the first implicit argument: instead of an instance, Python passes the class object itself (cls)—whether you callTreasuryStrip.from_record(r)on the class orstrip.from_record(r)on an instance (clsreceivestype(strip)).Like
self, the nameclsis a universal PEP 8 convention (classcannot be used because it is a reserved keyword). Becauseclsreceives no instance, a class method cannot read per-object attributes likeself.maturity, but it can read class attributes (cls.FACE_VALUE) and construct new instances viacls(...).The #1 practical job for
@classmethodis 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.56Look at why
cls(...)insideInstrument.from_recordis magic: we wrotefrom_recordonce inInstrument, yet callingTreasuryStrip.from_record(raw_row)passescls = TreasuryStripand returns aTreasuryStrip! Meanwhile, callingInstrument.from_record(raw_row)passescls = Instrument, which immediately hits the abstract-classTypeError—protecting the invariant from factory calls too. Standard-library examples includedict.fromkeys(["a", "b"], 0)anddatetime.fromisoformat("2026-11-30").Static methods and why they belong inside a class
Decorating a method with
@staticmethoddisables implicit first-argument binding altogether: Python passes neitherselfnorcls. Whether you callInstrument.is_valid_quantity(4)on the class orstrip.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:- Cohesion and discoverability:
"What counts as a valid Instrument quantity?"belongs conceptually toInstrument. Grouping it insideInstrumentkeeps related domain rules together inhelp(Instrument)and avoids polluting module namespaces or requiring extra imports. - Polymorphic overriding in subclasses: When
__init__callsself.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.- Cohesion and discoverability:
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 metaclassABCMeta) and decorate required methods with@abstractmethod. Defining the class succeeds; instantiating it (Instrument(...)) raisesTypeErrorat run time insideobject.__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)becomesTreasuryStrip.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 neitherselfnorcls. Used inside a class for namespace cohesion/discoverability and so subclasses can override helper rules when invoked throughself.helper(...)orcls.helper(...). selfandclsare conventions, not keywords: Python binds by parameter position (first argument), though PEP 8 universally mandates the namesselfandcls.
Common mistakes
- Using
@abstractmethodwithoutABC(orABCMeta): On a plain classclass Foo:,@abstractmethoddoes not preventFoo()from instantiating—ABCMetais what checks__abstractmethods__at creation time. - Assuming
class Empty(ABC): passcannot be instantiated: Inheriting fromABCwith zero unimplemented@abstractmethods leaves__abstractmethods__empty, soEmpty()succeeds. - Stacking
@abstractmethodin the wrong order: When combining decorators (such as@classmethodor@propertywith@abstractmethod),@abstractmethodmust be the innermost decorator right abovedef, orABCMetamay 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 raisesTypeErrorif the base is abstract!) when called asSubClass.from_record(...). - Bypassing static-method overrides via hardcoded class names: Calling
Instrument.is_valid_quantity(q)inside__init__ignores any override onLongOnlyStrip; callself.is_valid_quantity(q)orcls.is_valid_quantity(q)so polymorphism works. - Forgetting
boolsubclassesintin Python validation helpers:isinstance(True, int)evaluates toTrue(True == 1), so integer validators should guardnot isinstance(x, bool).
Follow-up questions
-
When a child class calls an inherited
@classmethodfactory, which class gets instantiated, and how would switching that factory to@staticmethodbreak subclassing? Called asTreasuryStrip.from_record(record), Python passescls = TreasuryStrip, soreturn cls(...)constructs and returns an instance ofTreasuryStripeven thoughfrom_recordwas defined onInstrument. Iffrom_recordwere a@staticmethod, Python would pass noclsparameter, forcing the body to hardcode a class name: hardcodingTreasuryStrip(...)breaks sibling subclasses likeSwap, while hardcodingInstrument(...)immediately crashes withTypeErrorbecauseInstrumentis abstract! -
Suppose a base class declares multiple
@abstractmethodhooks and a child class overrides only one of them—what happens at class-definition time versus instantiation time? SupposeInstrumentdeclares two abstract methods,price(self, curve)andduration(self, curve), andPartialStrip(Instrument)implementspricewithout implementingduration. Definingclass PartialStrip(Instrument):succeeds with zero error,PartialStrip.__abstractmethods__holdsfrozenset({'duration'}), and any attempt to instantiatePartialStrip(...)raisesTypeError: Can't instantiate abstract class PartialStrip without an implementation for abstract method 'duration'. In larger hierarchies, engineers intentionally write partial subclasses (likeBond(Instrument)) as intermediate building blocks for concrete leaves (TreasuryStrip(Bond)). -
In what design scenarios is structural typing with
typing.Protocolpreferable to inheriting from anabc.ABCbase class? AnABCuses nominal subtyping (a class conforms only by explicitly inheritingclass MyStrip(Instrument):), giving you shared concrete methods (market_value) and strict runtime instantiation guards.typing.Protocoluses structural subtyping (static duck typing: any class with a matchingdef price(self, curve) -> float:conforms automatically without inheriting anything), verified before runtime by type checkers likemypyorpyright. Reach forProtocolwhen decoupling libraries, typing third-party classes you cannot modify, or keeping lightweight test fakes inheritance-free; reach forABCwhen subclasses genuinely share implementation code or need runtime instantiation protection. -
If
count = 0is defined on the class body and an instance method executesself.count += 1, how do the instance dictionary and the class attribute change? Becausecount = 0is an immutable integer on the class, the class attribute stays0! Python expandsself.count += 1intoself.count = self.count + 1: the right-hand readself.countmissesself.__dict__and falls back toTradeCounter.count(0), computes0 + 1 = 1, and then the assignment writes'count': 1intoself.__dict__, creating an instance attribute that shadows (hides) the class attribute for that one object. To increment a true class-wide counter, writetype(self).count += 1(orcls.count += 1in a@classmethod); and beware mutable class attributes likeitems = [], whereself.items += [x]mutates the single shared list in place across all instances and bindsself.__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
- When a child class calls an inherited `@classmethod` factory, which class gets instantiated, and how would switching that factory to `@staticmethod` break subclassing?
- 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?
- In what design scenarios is structural typing with `typing.Protocol` preferable to inheriting from an `abc.ABC` base class?
- 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?
Similar questions
- Building and Unit Testing a FastAPI REST Endpoint Around Python Logic
- Under the Hood of Python Dicts: Hashing, Collisions, and Valid Keys
- Generator Mechanics, Lazy Evaluation, and Function Decorators in Python
- Python Environment Isolation, Package Managers, and Daily Linux Workflow
- Database Index Trade-Offs and Diagnosing Slow SQL Queries
- Python Concurrency: Processes, Threads, the GIL, and Asyncio
More Engelhart interview questions
- Weather-Driven Power Forecasting Pipeline for Energy Trading Medium
- Building and Unit Testing a FastAPI REST Endpoint Around Python Logic Medium
- Under the Hood of Python Dicts: Hashing, Collisions, and Valid Keys Medium Pro
- Generator Mechanics, Lazy Evaluation, and Function Decorators in Python Medium Pro
- Python Environment Isolation, Package Managers, and Daily Linux Workflow Medium Pro
- Database Index Trade-Offs and Diagnosing Slow SQL Queries Medium Pro
- Python Concurrency: Processes, Threads, the GIL, and Asyncio Medium Pro