Abstract Classes
Python's official way to enforce abstraction using the abc module.
The abc Module
Python provides the abc (Abstract Base Classes) module with two key tools: the ABC class to inherit from, and the @abstractmethod decorator to mark methods that must be implemented by child classes.
What is an Abstract Class?
An abstract class is a class that cannot be instantiated directly. It exists only as a blueprint for other classes. Think of it as a template that says, "Here are the methods you must have, now go implement them."
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, brand):
self.brand = brand
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
def describe(self): # concrete method (not abstract)
return f"Vehicle: {self.brand}"
# v = Vehicle("Toyota") # TypeError! Cannot instantiate abstract class
class Car(Vehicle):
def start(self):
print(f"{self.brand} car engine starts")
def stop(self):
print(f"{self.brand} car engine stops")
class Bicycle(Vehicle):
def start(self):
print(f"{self.brand} bicycle starts pedaling")
def stop(self):
print(f"{self.brand} bicycle brakes applied")
car = Car("Toyota")
bike = Bicycle("Trek")
car.start() # Toyota car engine starts
bike.start() # Trek bicycle starts pedaling
car.describe() # Vehicle: Toyota (inherited concrete method)
Abstract vs Concrete Methods
Abstract Methods
- Decorated with
@abstractmethod - Body is just
pass - Must be implemented by child classes
- Define the "contract" or interface
Concrete Methods
- Regular methods with full implementation
- Inherited as-is by child classes
- Can optionally be overridden
- Shared behavior across all subclasses
Important: If a child class does not implement all abstract methods, it also becomes abstract and cannot be instantiated.
Real-World: Payment System
Imagine building a payment system. You want all payment processors to have process() and refund() methods, but each provider implements them differently.
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def process(self, amount):
pass
@abstractmethod
def refund(self, amount):
pass
class StripePayment(PaymentProcessor):
def process(self, amount):
print(f"Processing ${amount} via Stripe")
def refund(self, amount):
print(f"Refunding ${amount} via Stripe")
class PayPalPayment(PaymentProcessor):
def process(self, amount):
print(f"Processing ${amount} via PayPal")
def refund(self, amount):
print(f"Refunding ${amount} via PayPal")
# Works with any payment processor!
def checkout(processor, amount):
processor.process(amount)
checkout(StripePayment(), 49.99)
checkout(PayPalPayment(), 29.99)
Best Practices
- Always import from
abc:from abc import ABC, abstractmethod - Use abstract classes when you need to enforce a consistent interface across multiple classes.
- Include concrete methods for behavior shared across all subclasses.
Common Mistakes
Forgetting to inherit from ABC -- using @abstractmethod alone does not enforce anything.
Implementing only some abstract methods in a child class, then trying to create an instance.
Making every method abstract when some should be concrete and shared.
Practice Exercises
Exercise 1: Shape with abc
Rewrite the Shape example from Lesson 6.1 using ABC and @abstractmethod. Add Circle, Rectangle, and Triangle subclasses.
Exercise 2: Employee System
Create an abstract Employee class with abstract method calculate_salary() and concrete method display_info(). Create FullTime and PartTime subclasses.
Exercise 3: Notification System
Build an abstract Notifier with abstract method send(message). Create EmailNotifier, SMSNotifier, and PushNotifier subclasses.
Summary
- The
abcmodule providesABCand@abstractmethodfor creating abstract classes. - Abstract classes cannot be instantiated -- they serve as blueprints.
- Abstract methods must be implemented by child classes; concrete methods are inherited.
- If a child skips any abstract method, it also becomes abstract.
- Next up: Interfaces -- the concept of pure contracts in Python.