Sub topic 1
Why Abstract Base Classes Exist
Prerequisites
You should know how to define classes, inherit from a base class, write instance methods, and handle exceptions with try and except.
Why Abstract Base Classes Exist
A plain base class can share code, but it does not always clearly state what every subclass must provide. An abstract base class (ABC) defines a required interface for a family of classes.
For example, every shape might need an area() method. A rectangle and a circle calculate area differently, but code using a shape can rely on that method existing. An ABC records this design rule and prevents incomplete objects from being created.
Creating an Abstract Base Class with ABC
Import ABC and inherit from it. ABC uses Python's ABCMeta metaclass, which tracks abstract methods and checks subclasses when they are instantiated.
from abc import ABC
class Shape(ABC):
pass
shape = Shape()
print(shape)This class has no abstract methods, so it can still be instantiated. Inheriting from ABC alone does not make a class abstract.
Declaring Required Methods with @abstractmethod
Use @abstractmethod to mark a method that subclasses must implement. The method can contain only ..., which is an ellipsis placeholder.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the shape's area."""
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.heightRectangle is concrete because it implements area(). A concrete class is one that has no remaining abstract methods.
Instantiating an Incomplete Subclass
If a subclass does not implement every abstract method, Python lets the class definition run but raises TypeError when you instantiate it.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
...
class BrokenShape(Shape):
pass
try:
BrokenShape()
except TypeError as exc:
print("TypeError:", exc)This delayed check lets you define intermediate abstract subclasses. It also means tests should create objects, not only import or define classes, when checking that implementations are complete.
Exercise
When does Python raise TypeError for BrokenShape?
Show answer
Python raises TypeError when BrokenShape() is called because area() is still abstract.