Sub topic 7
Abstract class methods and static methods
This chapter assumes you know how @classmethod, @staticmethod and @property work, and that you have used @abstractmethod on ordinary methods. Earlier chapters showed that Python refuses to instantiate a class that still has abstract methods. The same rule applies to class methods and static methods.
Why make them abstract?
Some obligations belong to the class and not to an instance:
- A class method often acts as an alternative constructor, such as
from_config. Each subclass knows how to build itself. - A static method can return a fixed fact about a subclass, such as a registry name. It needs neither
selfnorcls.
Marking these abstract forces every concrete subclass to provide them, in the same way as for instance methods.
Decorator order
@abstractmethod must be the innermost decorator, directly above the def line. @classmethod and @staticmethod go outside it.
from abc import ABC, abstractmethod
class Plugin(ABC):
@classmethod
@abstractmethod
def from_config(cls, config: dict) -> "Plugin":
"""Build an instance from a configuration dictionary."""
@staticmethod
@abstractmethod
def name() -> str:
"""Return the plugin's registry name."""
class EchoPlugin(Plugin):
def __init__(self, prefix: str) -> None:
self.prefix = prefix
@classmethod
def from_config(cls, config: dict) -> "EchoPlugin":
return cls(config.get("prefix", ""))
@staticmethod
def name() -> str:
return "echo"
plugin = EchoPlugin.from_config({"prefix": ">> "})
print(plugin.name(), repr(plugin.prefix))The output is echo '>> '.
The order matters because @abstractmethod works by setting the attribute __isabstractmethod__ = True on the function it receives. classmethod and staticmethod objects copy that attribute from the function they wrap. Python can then see that the wrapped function is abstract. If you reverse the order, @abstractmethod receives a classmethod object instead of a function. Older Python versions then fail with an AttributeError. In current versions the order is accepted, but the guideline for the correct order is still to put @abstractmethod innermost.
Same rules as other abstract methods
An abstract class method or static method is checked when you instantiate the class, not when you define it. If a subclass leaves one out, creating an instance raises TypeError.
from abc import ABC, abstractmethod
class Plugin(ABC):
@staticmethod
@abstractmethod
def name() -> str:
...
class Incomplete(Plugin):
pass
try:
Incomplete()
except TypeError as exc:
print("TypeError:", exc)The message names the missing method, for example name.
Calling the method on the class itself, such as Incomplete.name(), does not raise this error. Python only checks abstract methods when it creates an object. An abstract class method on the abstract base can still run if you call it directly. The abstract body here is just a docstring or ..., so it would return None.
Using an abstract class method as a factory
Abstract class methods work well with concrete code in the base class. The base class can call cls.from_config or cls.name() and trust that every concrete subclass defines them.
from abc import ABC, abstractmethod
class Plugin(ABC):
@classmethod
@abstractmethod
def from_config(cls, config: dict) -> "Plugin":
...
@staticmethod
@abstractmethod
def name() -> str:
...
@classmethod
def build_all(cls, configs: list[dict]) -> list["Plugin"]:
return [cls.from_config(c) for c in configs]
class UpperPlugin(Plugin):
def __init__(self, text: str) -> None:
self.text = text.upper()
@classmethod
def from_config(cls, config: dict) -> "UpperPlugin":
return cls(config.get("text", ""))
@staticmethod
def name() -> str:
return "upper"
items = UpperPlugin.build_all([{"text": "a"}, {"text": "b"}])
print([p.text for p in items], UpperPlugin.name())The output is ['A', 'B'] upper. build_all is a concrete class method. Because it uses cls, it calls the subclass's own from_config.
Common mistakes
| Mistake | Result |
|---|---|
| `@abstractmethod` above `@classmethod` | Wrong order. It may fail or not enforce, depending on the Python version. |
| Forgetting to override the static method | `TypeError` on instantiation. |
| Expecting an error when the subclass is defined | None is raised. The check happens on instantiation. |
| Overriding an abstract class method with a plain instance method | The subclass is concrete, but `cls.from_config(...)` calls break. |
Exercise
A base class declares @abstractmethod above @staticmethod on a method kind(). What should the order be, and when does Python report a subclass that forgets to define kind?
Show answer
Write @staticmethod first and @abstractmethod directly above the def, so that @abstractmethod is innermost. Python reports the missing method with a TypeError when you instantiate the subclass, not when you define it.
Exercise
In the Plugin example, build_all calls cls.from_config(c). Why does UpperPlugin.build_all(...) return UpperPlugin objects and not Plugin objects?
Show answer
build_all is a class method, so cls is the class it was called on, UpperPlugin. The call cls.from_config therefore runs UpperPlugin.from_config, which builds UpperPlugin instances.