abstract base class (ABC)
In Python, an abstract base class (ABC) is a class that can’t be instantiated on its own and is designed to be a blueprint for other classes, allowing you to define a common interface for a group of related classes.
ABCs allow you to define methods that must be created within any subclasses built from the abstract base class. This is useful for ensuring that derived classes implement particular methods from the base class, providing a consistent interface for different parts of your program.
To define an abstract base class, you inherit from abc.ABC
and use the @abstractmethod
decorator to mark methods that must be implemented by subclasses. Attempting to instantiate an abstract base class or a subclass that hasn’t implemented all abstract methods will raise a TypeError
exception.
Example
Here’s a simple example of how to define and use an abstract base class in Python:
animals.py
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
def jump(self):
return f"{self.__class__.__name__} is jumping"
Animal
is an abstract base class with an abstract method .speak()
and a regular method .jump()
. Subclasses must implement all methods marked with @abstractmethod
:
>>> from animals import Animal
>>> class Dog(Animal): pass
...
>>> Dog()
Traceback (most recent call last):
...
TypeError: Can't instantiate abstract class Dog
without an implementation for abstract method 'speak'
Here’s a correct implementation:
>>> class Dog(Animal):
... def speak(self):
... return "Woof Woof"
...
>>> dog = Dog()
>>> dog.speak()
'Woof Woof'
>>> dog.jump()
'Dog is jumping'
Dog
is a concrete class that inherit from Animal
and implement the .speak()
abstract method. It inherits the .jump()
methdo from Animal
.
Related Resources
Tutorial
Implementing an Interface in Python
In this tutorial, you'll explore how to use a Python interface. You'll come to understand why interfaces are so useful and learn how to implement formal and informal interfaces in Python. You'll also examine the differences between Python interfaces and those in other programming languages.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python Interfaces: Object-Oriented Design Principles (Course)
- Implementing an Interface in Python (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)