🐍 Python Advanced

What is Python's Abstract Base Classes?

Answer

Abstract Base Classes (ABCs) from the abc module define interfaces that subclasses must implement. Use ABCMeta metaclass or inherit from ABC: from abc import ABC, abstractmethod; class Shape(ABC): @abstractmethod def area(self) -> float: pass; @abstractmethod def perimeter(self) -> float: pass. Attempting to instantiate an abstract class raises TypeError. Concrete subclasses must implement all abstract methods. ABCs also support virtual subclassing: Shape.register(MyShape) — tells Python that MyShape is a Shape without inheriting (used for structural subtyping). The collections.abc module defines standard ABCs: Iterable, Iterator, Sequence, Mapping, Callable. These are used by type checkers and isinstance() checks: isinstance([], Sequence) returns True. ABCs bridge the gap between duck typing and strict interface enforcement.