1 - Abstract Classess Python
1 - Abstract Classess Python
Oriented Programming
PYTHON FOCUS INTERMEDIATE LEVEL
A deep dive into Abstract Base Classes, abstract methods, and the abc
module — the tools Python provides to enforce interface contracts, enable
polymorphism, and design robust, scalable software systems.
Topic Classification
Category
Object-Oriented Programming /
Design Principle
Difficulty
Intermediate — requires knowledge
of classes, inheritance,
polymorphism, and Python
decorators
Industry Relevance
Core to Django, Flask, SQLAlchemy,
plugin systems, testing (mocking),
and framework development
Recommended Path
Python Classes → Inheritance &
super() → Polymorphism →
Abstraction (ABCs) → Protocols →
Design Patterns
What Is Abstraction?
Abstraction in Python is the OOP principle of hiding implementation details and exposing only essential features. Python
implements abstraction through Abstract Base Classes (ABCs) using the abc module.
Think of a Vehicle — you know every vehicle can start() and stop(), but a generic "Vehicle" doesn't exist in the real world. You
program to the Vehicle interface, not to the concrete details.
Key Terminology
Abstract Base Class (ABC) A class inheriting from [Link] that cannot be instantiated.
Abstract method A method decorated with @abstractmethod; has no implementation in the abstract
class.
Concrete class A subclass that overrides all abstract methods; can be instantiated.
abc module Python's built-in module for defining abstract base classes.
Duck typing Python's dynamic approach to interfaces; ABCs provide an explicit alternative.
Virtual subclass A class registered via register() as an ABC subclass without explicit inheritance.
Concrete implementation A class that provides definitions for all inherited abstract methods.
Declare
Define Implement in Instantiate
Import ABC @abstractme
Abstract Subclass Concrete
thod
These five steps form the complete lifecycle of working with Abstract Base Classes in Python — from import to instantiation.
Why Does Abstraction Exist?
Problems It Solves What Happens Without ABCs?
Polymorphic collections
Store instances of concrete subclasses in a container ABCs provide an explicit, enforceable contract at
typed to the abstract base. class definition time — the best of all worlds.
Evolution & History
1990s 1
Python early versions had no formal ABCs; duck
typing was the norm.
2 2000–2005
PEP 245 (Interface Syntax) rejected. Python 2.2
introduced the NotImplementedError convention.
2007 3
PEP 3119 — Introducing Abstract Base Classes.
Implemented in Python 2.6 and 3.0.
4 2008–2012
abc module added; collections gains ABCs for
containers (Iterable, Sequence, MutableMapping).
2015–2020 5
@abstractmethod works with @property,
@classmethod, @staticmethod. Type checkers (mypy)
recognise ABCs. 6 Present
ABCs stable and widely used. PEP 544 introduces
Protocol for structural subtyping, complementing
ABCs.
Approach Limitation
Duck typing No compile-time enforcement; errors occur at runtime, possibly deep in code.
Raising NotImplementedError Only checked when method is called, not at class definition.
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Base(ABC):
@abstractmethod
def greet(self):
Mark Collect print("Base greeting")
Subclass
Define ABC Use ABCMeta @abstractme abstractmeth
overrides
thod ods
class Derived(Base):
def greet(self):
This internal mechanism ensures contracts are enforced at the earliest possible
super().greet()
moment — class creation, not method call time.
print("Derived greeting")
d = Derived()
[Link]()
# Base greeting
# Derived greeting
Pure ABC (Interface) ABC with Partial ABC with Abstract Properties
Only abstract methods, no concrete
Implementation Enforces property getters/setters.
methods or data. Forces full Mix of abstract and concrete Ideal for data validation and
implementation. Clean contract methods. Enables the Template computed attributes. Slightly more
definition. Method pattern and framework verbose.
hooks with code reuse.
class Drawable(ABC):
def role_description(self) -> str:
@abstractmethod
return "Manages team and projects"
def draw(self):
pass
emp1 = Developer("Alice", 50, 160)
emp2 = Manager("Bob", 8000)
class Point: # third-party, can't modify
print(emp1.calculate_salary()) # 8000.0
def draw(self):
print(emp2.role_description()) # Manages team and
print(f"Drawing point")
projects
# Employee() → TypeError [Link](Point)
p = Point(10, 20)
print(isinstance(p, Drawable)) # True
Hands-On Labs
1 2
BEGINNER INTERMEDIATE
Objective: Create an abstract Shape class with abstract Objective: Subclass [Link] to
methods area() and perimeter(). Implement Rectangle and create a Playlist class that logs every addition/removal.
Circle.
1. Import MutableSequence from [Link]
1. Import ABC and abstractmethod from abc 2. Define Playlist(MutableSequence) with self._items = []
2. Define Shape class inheriting ABC 3. Implement 5 required abstract methods with logging
3. Add @abstractmethod for area and perimeter print statements
4. Define Rectangle(width, height) and Circle(radius) 4. Test: create playlist, add songs, index, delete, append,
extend
5. Store instances in a list, iterate and print results
6. Try to instantiate Shape() — observe TypeError 5. Observe that append, extend, pop work automatically
class Playlist(MutableSequence):
def __init__(self):
self._items = []
def __len__(self):
return len(self._items)
p = Playlist()
[Link]("Song A") # uses insert internally
[Link]("Song B")
print(p[0]) # Accessing index 0 → Song A
Advantages & Disadvantages
✅ Enforces
Contracts
✅ Fail-Fast Safety ⚠️ Over- ⚠️ Learning Curve
Engineering Risk
Raises TypeError early at Requires understanding
Prevents incomplete class definition or Can lead to unnecessary ABC syntax, decorators,
objects; supports instantiation. complexity for simple and metaclasses.
Open/Closed Principle. scripts.
✅ Machine-
Checkable Docs
✅ Code Reuse ⚠️ Virtual Subclass ⚠️ Deep
Risk Hierarchies
ABCs can provide
Abstract methods act as concrete methods that all Virtual subclasses do not May encourage deep
clear, verifiable subclasses inherit. enforce method inheritance chains that
documentation. presence — use are hard to maintain.
carefully.
✅ Minimal Overhead
Abstract method check occurs only once at instantiation
⚠️ Breaking Changes
— no per-call cost. Adding abstract methods to a published ABC breaks all
existing subclasses.
Balanced View: Use ABCs for frameworks, plugins, and public APIs. Consider Protocols (PEP 544) for static type
checking without runtime overhead. Avoid ABCs for simple internal scripts where duck typing suffices.
Performance & Scalability
Performance Characteristics Scalability in Codebases
Backward Reliability
Minimal Memory Impact Compatibility
Fail-fast behaviour catches
The __abstractmethods__ frozenset is stored on the class Alternatives: add a new errors early. Virtual
object — negligible memory footprint. versioned ABC, or provide subclasses bypass method
a mixin with a default checking — use sparingly
implementation to avoid to avoid runtime
Guideline: Use ABCs freely — they will never be your
breaking changes. AttributeError.
performance bottleneck. Object creation and
attribute lookup overhead far outweighs any ABC
checks.
Design & Architectural Considerations
Template Method
1
ABC defines skeleton algorithm with abstract steps. Subclasses fill in the blanks.
Factory Method
2
Abstract creator declares factory method. Concrete creators return specific product types.
Strategy
3
ABC defines strategy interface. Concrete strategies implement interchangeable algorithms.
Command
4
ABC defines execute() method. Commands encapsulate actions as objects.
Observer
5
ABC defines update() method. Observers react to state changes in subjects.
Pure ABC vs partial Only abstract / mix of abstract and Pure ABC for interfaces; partial for
implementation concrete Template Method
Virtual subclassing vs explicit register() vs normal subclass Prefer explicit; register only for third-
inheritance party classes
ABC vs Protocol (PEP 544) Runtime enforcement / static checking ABC for runtime isinstance; Protocol for
only static typing
4 5
at class possible.
definition
Keyword No abstract =0
keyword
(use ABC)
Metaclass Yes No No
support (ABCMeta
)
Learning Summary & Key Takeaways
01 02 03
ABCs are defined with [Link] Subclasses must override all ABCs support concrete methods,
and @abstractmethod abstract methods properties, and class/static
A class with at least one abstract method Only then do they become concrete and
methods
cannot be instantiated — TypeError is instantiable. Partial overrides keep the They are not limited to pure interfaces —
raised. subclass abstract. they can provide shared implementations
too.
04 05
Use ABCs for frameworks, plugins, and large Virtual subclasses and __subclasshook__ enable
codebases duck-typing compatibility
For static type checking without runtime overhead, consider Use sparingly — they bypass method enforcement and can lead
Protocols (PEP 544) instead. to surprising runtime errors.
class AbstractClassName(ABC):
@abstractmethod
def required_method(self):
"""Must be overridden"""
pass
def concrete_method(self):
return "shared implementation"
class ConcreteClass(AbstractClassName):
def required_method(self):
return "implementation"
obj = ConcreteClass() # OK
# base = AbstractClassName() # TypeError