An abstract class defines a common interface for related subclasses. It acts as a template: subclasses must provide the marked methods before they can be instantiated. In Python, abstract base classes provide interface-like control while still using inheritance. section 8.3.4 section 8.5
Create an abstract base class by:
- Inheriting from ABC to identify the class as abstract. section 8.3.4
- Marking required methods with @abstractmethod. section 8.3.4
- Implementing those methods in every concrete subclass before creating instances. section 8.3.4
A predator interface
A Predator abstract class can require an eat(prey) method. Bear, Owl, and Chameleon each implement eat differently, while attempting to instantiate a subclass without eat raises a TypeError. 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')
Inspect the complete Predator example, including ABC, abstractmethod, subclass implementations, and concrete calls. section 8.3.4
Abstract classes also support practical refactoring. A Command base class can require execute(data), while command subclasses implement it. Keeping the signature consistent improves substitutability; explicit optional arguments are preferred to unrestricted variable arguments when flexibility is unnecessary. section 8.4.1





