Define an abstract base class with abc.ABC.
How It Works
abc.ABC and @abstractmethod let a class declare required methods. Subclasses that do not provide concrete implementations remain abstract and cannot be instantiated normally.
An abstract method may include an implementation useful to subclasses calling super().
Step-by-Step Example
from abc import ABC, abstractmethod
class DataStore(ABC):
@abstractmethod
def load(self):
pass
class MemoryStore(DataStore):
def load(self):
return ["item-a", "item-b"]
print(MemoryStore().load())
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
['item-a', 'item-b']
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create an ABC for a notifier with one abstract send() method.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Trying to instantiate an abstract class that still has unimplemented abstract methods.
- Assuming an ABC automatically validates every semantic behavior of an implementation.
Key Takeaways
- Define an abstract base class with abc.ABC.
- abc.ABC and @abstractmethod let a class declare required methods.
- An abstract method may include an implementation useful to subclasses calling super().