track
Python Abstract Classes: A Comprehensive Guide with Examples
A key component of modern software development is object-oriented programming (OOP), which gives programmers the ability to organize code in a scalable, modular, and reusable manner. Abstract classes are one of the numerous OOP concepts that are essential for creating a template that other classes can use. This post will explain abstract classes, their benefits, and how to use Python's abc module to build them successfully.
If you're new to Python, you can learn how to work with modules and packages, work with built-in data types, and write custom functions with our skill track.
What is an Abstract Class?
An abstract class is like a template for other classes. It defines methods that must be included in any class that inherits from it, but it doesn’t provide the actual code for those methods.
Think of it as a recipe without specific ingredients—it tells you what steps to follow, but the details depend on the subclass.
Example:
Let’s say you’re building a program to calculate the area of different shapes.
- You create an abstract class called
Shape
that says every shape must have anarea()
method. - But
Shape
doesn’t define howarea()
works—because the formula depends on the type of shape. - Each specific shape (like a
Circle
orRectangle
) inherits fromShape
and provides its own version ofarea()
.
If you're looking to learn more about key Python concepts, you can enroll in our Intermediate Object-Oriented Programming in Python course.
Why use abstract classes in Python?
Abstract classes are useful when you wish to:
- Enforce method implementation: An abstract class's methods function as a contract, requiring each subclass to supply its own implementation. This lowers the possibility of inconsistent or lacking implementations by ensuring that specific functionality is present across all derived classes.
- Encourage code reuse: abstract classes can have both concrete and abstract methods. The concrete methods greatly reduce code duplication and encourage the DRY (Do not Repeat Yourself) principles by providing shared functionality that can be inherited by all subclasses.
- Improve readability and maintainability: Abstract classes help developers better comprehend the structure and functionality of the software by providing a consistent and transparent framework. This structure makes the code easier to maintain by enforcing design principles like single responsibility and separation of responsibilities.
- Encourage polymorphism: Abstract classes make it possible to write general code that works well with a variety of subclasses. Developers can create functions or methods that can handle any subclass of the abstract class thanks to this flexibility, which increases the code's extensibility and adaptability to changes in the future.
You can make sure that any subclass, such as Dog
or Cat
, implements its implementation of the speak
method, for instance, if you have an abstract class Animal
with an abstract method speak
. Your code becomes reliable and predictable as a result of this uniformity.
Learn Python From Scratch
The abc Module in Python
The abc
module in Python offers strong built-in support for abstract classes. The module, which stands for "Abstract Base Classes," gives programmers the necessary tools to create abstract classes, including the abstractmethod
decorator and the ABC class.
By defining abstract methods and requiring their implementation in subclasses, these tools help you maintain uniformity and conformity to a predetermined interface. By requiring the implementation of essential methods in all derived classes and permitting the partial implementation of common functionality in abstract base classes, the module also encourages improved design patterns.
Because of this, the ABC module is a crucial component for organizing scalable, robust, and stable Python applications.
Creating a Python Abstract Class
Two essential components are introduced in the ABC module:
Abstract Base Class, or ABC
The ABC class is a built-in Python feature that serves as a fundamental basis for developing abstract classes. You must inherit from ABC to define an abstract class. The class is abstract and cannot be instantiated directly, as indicated by this inheritance. By acting as blueprints, abstract classes make sure that any concrete subclass abides by a set of rules.
You can define abstract methods inside an abstract class by using the abstractmethod
decorator. Any concrete subclass must implement and override abstract methods, which are placeholders. This makes the code consistent and predictable by guaranteeing that all derived classes offer functionality for the designated methods. A useful tool for requiring method implementation while giving subclasses flexibility in how they meet these requirements is the abstractmethod
decorator.
Here’s a basic example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
# Uncommenting the following line will raise an error because we’re missing method implementations
# shape = Shape() # TypeError: Can't instantiate abstract class Shape with abstract methods #area, perimeter
circle = Circle(5)
print(f"Area: {circle.area()}")
print(f"Perimeter: {circle.perimeter()}")
Area: 78.53975
Perimeter: 31.4159
If you’re looking for more practical Python projects, check out our list of the top 60 Python projects for developers at all levels.
How the abc module enforces method implementation
Any subclass of an abstract class is guaranteed to implement the decorated methods thanks to the abstractmethod
decorator. As a precaution, it stops subclasses from being created that do not have the necessary capabilities.
Python reports a TypeError
when a subclass is attempted to be instantiated if it does not override all abstract methods. This stringent enforcement lowers the likelihood of defects and improves code stability by assisting developers in identifying implementation flaws early.
It also guarantees that all concrete subclasses follow the abstract class's intended behavior and design.
For instance:
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
# Missing area and perimeter implementation
# This will raise an error
rectangle = Rectangle(5, 10)
TypeError: Can't instantiate abstract class Rectangle with abstract methods area, perimeter
Abstract Class Methods in Python
In Python, defining an abstract class entails using the abstractmethod
decorator and subclassing from ABC
. By doing this, programmers can lay the groundwork for other classes by defining the methods that need to be used.
Here is a thorough, step-by-step procedure:
- Bring in the necessary modules: Importing
ABC
andabstractmethod
from theABC
module should come first. To define abstract classes and methods, these tools are necessary. - Construct a class based on
ABC
: Create a new class and setABC
as its inheritor. The class is abstract and cannot be instantiated directly, as indicated by this inheritance. - Define abstract methods using
@abstractmethod
: To specify which methods subclasses must override, use the@abstractmethod
decorator. In essence, these methods serve as placeholders, guaranteeing that all derived classes carry out the necessary operations.
Step-by-step example of defining an abstract class
Here’s a practical example to demonstrate:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Car(Vehicle):
def start_engine(self):
print("Car engine started")
def stop_engine(self):
print("Car engine stopped")
# Instantiating the abstract class directly will raise an error
# vehicle = Vehicle()
car = Car()
car.start_engine()
car.stop_engine()
Car engine started
Car engine stopped
This guarantees that the start_engine
and stop_engine
functions are implemented by any subclass of Vehicle.
Practical example: abstract class implementation
Take a look at a more thorough illustration using a Vehicle
class:
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, brand):
self.brand = brand
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Motorcycle(Vehicle):
def start_engine(self):
print(f"{self.brand} motorcycle engine started")
def stop_engine(self):
print(f"{self.brand} motorcycle engine stopped")
motorcycle = Motorcycle("Yamaha")
motorcycle.start_engine()
motorcycle.stop_engine()
Yamaha motorcycle engine started
Yamaha motorcycle engine stopped
This illustrates how abstract classes allow implementation flexibility while enforcing a consistent interface.
Python Abstract Base Class Example
Now that we've seen how abstract base classes define a contract for subclasses, let's explore how concrete classes fulfill these requirements by implementing all the abstract methods.
Concrete class inheriting from an abstract class
A subclass that implements every abstract method of an abstract class is called a concrete class. This indicates that the concrete class provides specific implementations for all necessary methods, thereby fulfilling the contract established by the abstract class.
For instance:
from abc import ABC, abstractmethod
class Appliance(ABC):
@abstractmethod
def turn_on(self):
pass
@abstractmethod
def turn_off(self):
pass
class WashingMachine(Appliance):
def turn_on(self):
print("Washing machine is now ON")
def turn_off(self):
print("Washing machine is now OFF")
machine = WashingMachine()
machine.turn_on()
machine.turn_off()
Washing machine is now ON
Washing machine is now OFF
Creating instances and enforcing rules
Python prevents you from immediately instantiating an abstract class. Because it ensures that any subclass generated from the abstract class will adhere to the necessary contract provided by its abstract methods, this is an essential aspect of abstract classes.
For instance, a TypeError
will be raised if you try to instantiate appliance = Appliance()
This limitation guarantees that abstract classes function only as blueprints and are free of abuse. Python allows the creation of instances of WashingMachine
while maintaining the contract specified in Appliance
by implementing all of the abstract methods in WashingMachine
. By guaranteeing that every feature specified in the abstract class is completely implemented in its concrete subclasses, this enforcement improves the codebase's integrity.
Abstract Properties and Initialization
With this foundation, let's dive deeper into how Python supports abstract properties using the @property’ and
@abstractmethod’ decorators, enabling developers to enforce attribute consistency alongside methods.
Using abstract properties in Python
Abstract classes can specify properties that subclasses must implement in addition to methods. This feature enables developers to impose a uniform interface for properties that subclasses must declare in addition to methods.
To guarantee that every subclass provides its implementation, abstract properties can be specified using the @property
decorator in combination with @abstractmethod
. When creating classes that need read-only or computed attributes that are essential to the class's operation, this method is especially helpful.
Example: abstract class with properties
Here’s an example:
from abc import ABC, abstractmethod
class Animal(ABC):
@property
@abstractmethod
def sound(self):
pass
class Bird(Animal):
@property
def sound(self):
return "Chirp"
bird = Bird()
print(bird.sound)
Chirp
The Animal
abstract class's condition is met by the Bird
class's sound
feature.
When to Use Python Abstract Classes
Abstract classes are ideal for scenarios such as:
- When designing frameworks or libraries where particular behavior needs to be enforced: In complicated systems, abstract classes can establish a unified set of guidelines or interfaces that all subclasses must adhere to, guaranteeing consistency and lowering mistakes.
- Implementing consistent APIs across classes: Developers can guarantee that all derived classes offer a standardized and predictable means of communicating with the application or library by defining abstract methods.
- Supplying a foundational framework for a class hierarchy: A hierarchy of related classes can be created using abstract classes as a guide. By permitting customization in subclasses and allowing developers to declare shared behaviors and characteristics in the abstract class, this structure encourages reusability and minimizes duplication.
Best practices
When a precise contract for subclasses needs to be established, use abstract classes. Abstract classes are useful when you need to apply a specific structure or behavior to several derived classes. They help in making sure that every subclass adheres to a standard design, which improves code predictability and makes maintenance easier.
If every method can have a default implementation, do not use abstract classes. In certain situations, a concrete base class might be a better option to cut down on complexity while preserving the ability to reuse shared functionality.
Make sure abstract classes are clear and simple, defining only the most important attributes and methods. It might be challenging to construct and maintain an abstract class if it has too many criteria. Instead, concentrate on the essential aspects that the derived classes must have.
Conclusion
Python's OOP toolkit includes abstract classes, which are a powerful tool that allows programmers to create reliable and maintainable programs. You may promote clarity, reusability, and extensibility in your applications by defining abstract classes and enforcing a uniform interface across subclasses with the help of the ABC module. Writing better, more dependable code can be achieved by implementing abstract classes, regardless of the size of the system you are working on.
Whether you're designing robust object-oriented programs, enforcing consistent interfaces, or creating scalable applications, mastering Python abstract classes enhances your ability to write efficient and maintainable code. Boost your Python knowledge today with our comprehensive Python Fundamentals skill track.
Python Abstract Class FAQs
How do you define an abstract method in Python?
An abstract method is defined using the @abstractmethod
decorator from the abc
module. It serves as a placeholder and must be overridden by any subclass.
Can you instantiate an abstract class in Python?
No, you cannot instantiate an abstract class directly. Python will raise a TypeError
if you try to create an object of an abstract class.
What is the purpose of the `abc` module in Python?
The abc
module provides the ABC
class and abstractmethod
decorator to define and enforce abstract classes and methods in Python.
Can an abstract class have regular (concrete) methods?
Yes, an abstract class can have concrete methods with implementation. These methods can be inherited and used by subclasses.

Top Python Courses
course
Intermediate Object-Oriented Programming in Python
track
Python Developer
tutorial
Encapsulation in Python: A Comprehensive Guide
tutorial
Python Data Classes: A Comprehensive Tutorial
tutorial
Introduction to Python Metaclasses
tutorial
Inner Classes in Python
tutorial
Object-Oriented Programming in Python (OOP): Tutorial
tutorial
Python Classes Tutorial

DataCamp Team
3 min