Python ABCs and the Three Kinds of Methods Explained
Data Structure DesignModel answerLast updated
Explain how abstract base classes work in Python and how instance, class and static methods differ in binding, inheritance behavior and typical use.
You are asked to explain Python's object-oriented basics, as you would in a spoken technical screen. Use the skeleton below as the reference point:
class Instrument:
def price(self, curve): ...
@classmethod
def from_record(cls, record): ...
@staticmethod
def is_valid_quantity(quantity): ...
Part 1: Abstract classes
- What is an abstract class, and what is it for?
- Can you create an instance of one directly? Say exactly when and how it fails, and what a subclass must do to be instantiable.
Part 2: Kinds of methods
- How does an instance method differ from a class method?
- What do
selfandclsrefer to? Are they keywords? - What is a static method?
- A static method gets neither the instance nor the class. Why define it inside a class instead of at module level?
A strong answer is precise about how methods are bound, gives a use case for each kind, explains what happens under inheritance, and includes a short correct code example. You may mention how other languages differ, but focus on Python's abc module.
Hints
Hint 1
Python does not enforce abstractness on its own. Think about which base class or metaclass and which decorator make instantiation fail, and at what moment the error is raised.
Hint 2
Functions stored in a class are descriptors. Ask what gets passed as the first argument when you access the same function through an instance, through the class, or after wrapping it in classmethod or staticmethod.
Hint 3
For the alternative-constructor question, compare writing `return Instrument(...)` with `return cls(...)` inside a classmethod, then think about what a subclass gets back in each case.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Abstract classes
What it is. An abstract class defines a contract for a family of related classes and is not meant to be used on its own. It can declare methods that every subclass must provide (the interface) and also supply concrete methods and state that subclasses inherit (shared implementation). That mix is what separates it from a pure interface.
How Python does it. Inherit from abc.ABC (whose metaclass is ABCMeta) and mark required methods with @abstractmethod:
from abc import ABC, abstractmethod
class Instrument(ABC):
def __init__(self, quantity):
self.quantity = quantity
@abstractmethod
def price(self, curve):
"""Return the present value."""
def notional_value(self, curve): # concrete, shared
return self.quantity * self.price(curve)
Can it be instantiated? Not while any abstract method is unimplemented. Instrument(10) raises TypeError: Can't instantiate abstract class ... with abstract method price. Key details:
- The error occurs at instantiation, not when the class or subclass is defined. A subclass that forgets to override is fine until you call it.
- The check is based on the class's set of unresolved abstract names. A subclass becomes concrete once it overrides all of them. A partial override is still abstract.
- A class that inherits from
ABCbut declares no abstract methods can be instantiated. Abstractness comes from@abstractmethod, not from inheritingABC. - Without
ABC,@abstractmethodis not enforced at all. - Abstract methods may have a body, which subclasses can reach with
super(). Abstract properties and class methods are also possible. Put@abstractmethodinnermost, directly abovedef, under@classmethodor@property.
Trade-off versus the cheap alternative. Raising NotImplementedError in the base method also signals "override me", but it only fails when the method is called, possibly deep in production. ABC fails early, at construction. For purely structural contracts without inheritance, typing.Protocol is a lighter option, checked by type checkers rather than at runtime.
Part 2: Instance, class and static methods
All three are plain functions stored in the class namespace. What differs is the descriptor wrapping them, which decides what is passed in automatically when you look the method up.
| Kind | Decorator | First argument | Can reach |
|---|---|---|---|
| Instance method | none | the instance (self) | instance state and class state (through self) |
| Class method | @classmethod | the class (cls) | class state and other class methods, but no instance |
| Static method | @staticmethod | nothing implicit | only what you pass in (or globals) |
Instance methods. Accessing obj.price produces a bound method with obj already supplied as the first argument. Use them for behavior that depends on a particular object's data. Calling Instrument.price(obj, curve) also works because it is just a function. The binding happens only on instance access.
Class methods. @classmethod binds the class instead. Crucially, it is the class the call went through, so Bond.from_record(r) passes Bond, not the base class. Typical uses are alternative constructors (parsing from a record, a string, a file), factories and operations on class-level state such as registries or counters.
self and cls. They are only naming conventions for the first parameter, not keywords. self is the instance, cls is the class (an object itself, usually type(self)). Linters expect the conventional names, but the language doesn't require them.
Static methods. @staticmethod returns the underlying function unchanged, with no automatic first argument whether you call it through the class or an instance. It behaves like a module-level function that happens to live in the class namespace.
Why put a static method in a class?
- Cohesion and discoverability. A validator such as
is_valid_quantityis conceptually part of the type, soInstrument.is_valid_quantity(5)documents that relationship and avoids polluting the module namespace. - Overridability. If other methods call it as
self.is_valid_quantity(...)orcls.is_valid_quantity(...), subclasses can override the rule (for example, fractional quantities allowed for one product). A module-level function can't be customized that way. - Honest signature. It signals to readers that the function touches no instance or class state.
The honest caveat: if nothing about the function relates to the class, a module-level function is often cleaner. Static methods are a organizational choice, not a necessity.
Putting it together, with inheritance
from abc import ABC, abstractmethod
class Instrument(ABC):
def __init__(self, quantity):
if not self.is_valid_quantity(quantity):
raise ValueError("bad quantity")
self.quantity = quantity
@abstractmethod
def price(self, curve): ...
@classmethod
def from_record(cls, record):
return cls(record["quantity"]) # not Instrument(...)
@staticmethod
def is_valid_quantity(quantity):
return quantity > 0
class Bond(Instrument):
def price(self, curve):
return self.quantity * curve.discount(5)
b = Bond.from_record({"quantity": 100}) # a Bond, because cls is Bond
Instrument.from_record({"quantity": 1}) # TypeError: still abstract
Observations a good answer makes:
from_recordreturns aBondwhen called onBondonly because it usescls. HardcodingInstrument(...)would break subclasses (and here would fail outright because the base is abstract).- A class method can be called on the abstract base itself, but it fails if it tries to instantiate it.
__init__callsself.is_valid_quantity, so a subclass overriding the static method changes validation without touching the constructor.
Common mistakes
- Saying "class methods belong to the class, instance methods to the object". Both live in the class. The difference is what gets bound.
- Believing inheriting from
ABCalone makes a class uninstantiable. - Expecting the abstract-method error at class definition time.
- Using
@staticmethodand hardcoding the class name inside it, which defeats polymorphism. Use@classmethodwhen you need the class. - Treating
selfandclsas reserved words. - Using a class method that mutates class attributes without realizing subclasses may share or shadow that state.