Python › Metaclasses & Class Customization
How do abstract base classes (ABCs) use a metaclass to enforce that subclasses implement required methods?
AdvancedAnswer
The abc module's ABCMeta metaclass tracks methods decorated with @abstractmethod, and when you attempt to instantiate a class (not subclass, but instantiate) that hasn't overridden all abstract methods, ABCMeta's __call__ raises TypeError before __init__ even runs. This enforces an interface contract at instantiation time rather than only failing later when a missing method is actually called.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
try:
Shape() # TypeError: Can't instantiate abstract class
except TypeError as e:
print(e)Real-world example A plugin interface defines an abstract PaymentProcessor base class with abstractmethod charge() and refund(), guaranteeing every concrete payment integration implements both before it can even be instantiated.