🐍 Python Advanced

What is Python's Abstract Base Classes?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

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.

Pro Tip

This topic has Python-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.