Sub topic 2
Sharing Behavior with Concrete Methods
Prerequisites: you should know Python classes, inheritance, decorators, properties, and try/except.
An abstract base class (ABC) can require subclasses to provide certain operations while implementing shared behavior once. A concrete method is a normal method with a body. It can call an abstract method supplied by each subclass. This pattern is often called a template method.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the shape's area."""
def describe(self) -> str:
return f"{type(self).__name__}: {self.area():.2f} square units"
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.height
print(Rectangle(2, 3).describe())Shape.describe() contains shared behavior. It relies on area(), but Shape does not know how every shape calculates its area.
Abstract Properties
A property can be abstract too. Put @property above @abstractmethod. The subclass must then define a property with the same name.
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Return the balance in cents."""
class SavingsAccount(Account):
def __init__(self, cents: int) -> None:
self._cents = cents
@property
def balance(self) -> int:
return self._centsThe decorator order matters. @abstractmethod must be closest to the method definition.
Abstract Class and Static Methods
For a class method or static method, place @abstractmethod closest to def:
class Plugin(ABC):
@classmethod
@abstractmethod
def from_config(cls, config: dict) -> "Plugin":
"""Create an instance from configuration."""
@staticmethod
@abstractmethod
def name() -> str:
"""Return the plugin name."""A concrete subclass must implement both methods. The class method receives cls; the static method receives neither self nor cls.
Using `isinstance` and `issubclass`
ABCs work with normal type checks:
print(isinstance(Rectangle(2, 3), Shape)) # True
print(issubclass(Rectangle, Shape)) # TrueThese checks follow inheritance and can also include registered virtual subclasses. They do not prove that an arbitrary object has every method expected by an ABC unless the relationship was declared through inheritance, registration, or a carefully written __subclasshook__.
Exercise
Why can Shape.describe() call self.area() even though Shape does not implement area()?
Show answer
The method is resolved on the concrete subclass at runtime, where Rectangle.area() supplies the implementation.