abstractmethod is a decorator from Python’s abc module that marks a method as required by every concrete subclass. It turns an abstract base class into a template for shared behavior: subclasses must provide the marked method before they can be instantiated. section 8.3.4
Listing 8.4. Using abstract base classes to enforce an interface
from abc import ABC, abstractmethod
class Predator(ABC): #1
@abstractmethod #2
def eat(self, prey): #3
pass #4
class Bear(Predator): #5
def eat(self, prey): #6
print(f'Mauling {prey}!')
class Owl(Predator):
def eat(self, prey):
print(f'Swooping in on {prey}!')
class Chameleon(Predator):
def eat(self, prey):
print(f'Shooting tongue at {prey}!')
if __name__ == '__main__':
bear = Bear()
bear.eat('deer')
owl = Owl()
owl.eat('mouse')
chameleon = Chameleon()
chameleon.eat('fly')
A Predator base class marks eat as abstract, while Bear, Owl, and Chameleon each provide their own implementation. section 8.3.4
Use abstractmethod to make an interface explicit and catch incomplete subclasses early:
- Import ABC and abstractmethod, then inherit the base class from ABC. section 8.3.4
- Place @abstractmethod above each required method and define a consistent method signature. section 8.3.4 section 8.4.1
- Expect TypeError when code tries to instantiate a subclass that has not implemented every abstract method. section 8.3.4
Commands with a shared execute method
A Command abstract base class can require execute(data). Existing command classes inherit from Command and normalize their methods to accept the same argument, preserving substitutability while allowing each command to act on data. section 8.4.1
